题目描述
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
题意:有A,B两个上下两个沙漏,共x克,按每秒一克的速度从上漏斗落到下漏斗,并且会在t1,t2....tk时间处
进行上下翻转,有q个问题,如果初始值是a,问在时间 t 时刻的A中沙漏还剩多少克沙子。初始A在上。
思路:
如果对每个问题一遍一遍的初始遍历,会超时。题目已经给出m个问题中,确保了时间是递增的。
所以,如果不考虑初始状态是多少克,只需遍历一次就能求出m次问题中指定的t时候的A中的沙子的多少,
所以在这个基础上每个查询再考虑上初始状态a就可以了,所以只遍历一次。
a的状态大小,在第一次漏的时候只有两种
1.:因为第一次A在上,A有 1.漏完,A中剩余为0,就是low=0,代替的状态 2.未漏完有剩余,就是sum+num的状态
2.:经过一次翻转,A 有 1.被填满,A中剩余x,就是up=x的状态 2,未满,就是sum+num的状态
3.。。。以后每次都是以上两个状态的重复,最后进行 函数 judje(sum+num,low,up)
#include<bits/stdc++.h>
using namespace std;
int x,k,q;
int t[100010];
int judje(int u,int v=0,int w=x)
{
if(u<v)
return v;
if(u>w)
return w;
return u;
}
int main()
{
scanf("%d%d",&x,&k);
int i;
t[0]=0;
for(i=1;i<=k;i++)
{
scanf("%d",&t[i]);
}
scanf("%d",&q);
int low=0,up=x,p=1,sum=0,flag=-1,tt,a,num;
while(q--)
{
scanf("%d%d",&tt,&a);
while(tt>=t[p]&&p<=k)
{
num=flag*(t[p]-t[p-1]);
sum+=num;
low=judje(low+num);
up=judje(up+num);
p++;
flag=-flag;
}
int cnt=judje(flag*(tt-t[p-1])+judje(sum+a,low,up));
printf("%d\n",cnt);
}
return 0;
}
判断即可.