題目描述
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb.
The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per second. When the upper bulb no longer contains any sand, nothing happens.
Initially at time 0, bulb A is the upper bulb and contains a grams of sand; bulb B contains X−a grams of sand (for a total of X grams).
We will turn over the sandglass at time r1,r2,..,rK. Assume that this is an instantaneous action and takes no time. Here, time t refer to the time t seconds after time 0.
You are given Q queries. Each query is in the form of (ti,ai). For each query, assume that a=ai and find the amount of sand that would be contained in bulb A at time ti.
Constraints
1≤X≤109
1≤K≤105
1≤r1<r2<..<rK≤109
1≤Q≤105
0≤t1<t2<..<tQ≤109
0≤ai≤X(1≤i≤Q)
All input values are integers.
樣例輸入
180 3 60 120 180 3 30 90 61 1 180 180
樣例輸出
60 1 120
思路:假設開始初始值爲0那麼在任意時間點 其他的初始值都是大於等於以0爲初始點的。
同理,初始值爲X,其他初始值都是小於等於他的。
直接記錄從開始到查詢時間點的變化總值加上每次查詢的初始值,然後與0,X爲初始值到此時間點的值比對,如果超過範圍,說明已經0和X跑的線路一樣了,直接賦值,然後計算。(黑貓的思路,比賽的時候想不到,感覺有那麼點道理,還需再想想)
代碼:
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
using namespace std;
typedef long long LL;
const int maxn = 1e5+5;
int x;
int n;
int r[maxn];
int main()
{
scanf("%d%d",&x,&n);
r[0]=0;
for (int i=1;i<=n;i++) scanf("%d",r+i);
int L = 0;
int R = x;
int tmp = 0;
int pos = 1;
int Q;
scanf("%d",&Q);
int t,a;
while(Q--)
{
scanf("%d%d",&t,&a);
while(pos<=n && r[pos]<=t)
{
tmp+=(r[pos]-r[pos-1])*(pos&1?-1:1);
L+=(r[pos]-r[pos-1])*(pos&1?-1:1);
R+=(r[pos]-r[pos-1])*(pos&1?-1:1);
if(L<0) L=0;
if(L>x) L=x;
if(R<0) R=0;
if(R>x) R=x;
pos++;
}
// printf("%d %d %d ",pos,L,R);
int ans = a+tmp;
if(ans<L) ans = L;
if(ans>R) ans = R;
ans += (t-r[pos-1])*((pos)&1?-1:1);
if(ans<0) ans = 0;
if(ans>x) ans = x;
printf("%d\n",ans);
}
return 0;
}
(照搬 :) )