Sandglass
时间限制: 1 Sec 内存限制: 128 MB
提交: 393 解决: 101
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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克,按每秒一克的速度从上漏斗落到下漏斗会在r1,r2....rn时间处,进行上下n次翻转,有m个问题,如果初始值是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.。。。以后每次都是以上两个状态的重复,最后进行 函数 panduan(sum+num,low,up)判断即可.
感悟:怎么说呢,明明是到模拟题做出了思维题的感觉,刚开始的时候用的直接暴力,没有优化,超时,后来看了看别人代码,只跑一边即可。
#include<bits/stdc++.h>
using namespace std;
int a[100010],x,n,m;
int judge(int tt,int low=0,int up=x)
{
if(tt<low) return low;
if(tt>up) return up;
return tt;
}
int main()
{
scanf("%d%d",&x,&n);
a[0]=0;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
int low=0,up=x,k=1,sum=0,flag=-1,t,b,num;
while(m--){
scanf("%d%d",&t,&b);
while(t>=a[k]&&k<=n){
num=flag*(a[k]-a[k-1]);
sum+=num;
low=judge(low+num);
up=judge(up+num);
k++;
flag=-flag;
}
int ans=judge(flag*(t-a[k-1])+judge(sum+b,low,up));
printf("%d\n",ans);
}
return 0;
}