题目描述
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
#include <bits/stdc++.h>
#define N 100050
using namespace std;
//pair<int,int>s[N];
struct node{
int t,a;
}s[N];
int main()
{
int sand;
int k;//k个时间点
int time[N];
scanf("%d %d",&sand,&k);
for(int i=1;i<=k;i++)
scanf("%d",&time[i]);
int q;//q次查询
scanf("%d",&q);
for(int i=0;i<q;i++)scanf("%d %d",&s[i].t,&s[i].a);
long long MIN=0,MAX=sand,NOW=0,ki=1,sign=-1;
for(int i=0;i<q;i++)
{
while(ki<=k&&time[ki]<=s[i].t)//ki控制一共查询几次
{
long long now=time[ki]-time[ki-1];
now*=sign;
sign*=-1;
MIN+=now;
MIN=max(MIN,(long long)0);
MIN=min(MIN,(long long)sand);
MAX+=now;
MAX=max(MAX,(long long)0);
MAX=min(MAX,(long long)sand);
NOW+=now;
ki++;
}
long long now=s[i].t-time[ki-1];
now*=sign;
long long ans=s[i].a+NOW;
if(ans<MIN)ans=MIN;
if(ans>MAX)ans=MAX;
ans+=now;
ans=max(ans,(long long)0);
ans=min(ans,(long long)sand);
printf("%d\n",ans);
}
return 0;
}