标签:
题意:在一个0到L的坐标上,0是在某个位置摆个蛋糕,然后1是吃蛋糕,但是吃的必须是离自己最近的,若没有蛋糕就不动,若有两个蛋糕与其距离相等,那么我们选择上一步的方向来吃蛋糕,问最后这个人走了多远
思路:用两个队列应该就可以很简单的完成,但是想到了线段树,就写个线段树,而线段树一样维护的是最大值和最小值,不过这两个值都是对应的位置,那么对于队列来说肯定就是也维护这两个值,然后讨论处理一下就行了
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; typedef unsigned long long ull; const int inf=0x3f3f3f3f; const ll INF=0x3f3f3f3f3f3f3f3fll; const int maxn=100010; int num[maxn],max1[maxn<<2],min1[maxn<<2]; void pushup(int node){ max1[node]=max(max1[node<<1],max1[node<<1|1]); min1[node]=min(min1[node<<1],min1[node<<1|1]); } void update(int pos,int val,int le,int ri,int node){ if(le==ri){ if(val) max1[node]=min1[node]=pos; else max1[node]=0,min1[node]=inf; return ; } int t=(le+ri)>>1; if(pos<=t) update(pos,val,le,t,node<<1); else update(pos,val,t+1,ri,node<<1|1); pushup(node); } int queryL(int l,int r,int le,int ri,int node){ if(l<=le&&ri<=r) return max1[node]; int t=(le+ri)>>1,ans=0; if(l<=t) ans=max(ans,queryL(l,r,le,t,node<<1)); if(r>t) ans=max(ans,queryL(l,r,t+1,ri,node<<1|1)); return ans; } int queryR(int l,int r,int le,int ri,int node){ if(l<=le&&ri<=r) return min1[node]; int t=(le+ri)>>1,ans=inf; if(l<=t) ans=min(ans,queryR(l,r,le,t,node<<1)); if(r>t) ans=min(ans,queryR(l,r,t+1,ri,node<<1|1)); return ans; } int main(){ int T,n,m,op,pos,cas=1; scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); memset(max1,0,sizeof(max1)); memset(min1,inf,sizeof(min1)); memset(num,0,sizeof(num)); int dir=1,ans=0,now=1; for(int i=1;i<=m;i++){ scanf("%d",&op); if(op==0){ scanf("%d",&pos);pos++; if(num[pos]==0) update(pos,1,1,n+1,1); num[pos]++; }else{ if(num[now]>0){ num[now]--; if(num[now]==0) update(now,0,1,n+1,1); }else{ int len1,len2; int pos1=queryL(1,now,1,n+1,1); int pos2=queryR(now,n+1,1,n+1,1); if(pos1==0&&pos2==inf) continue; if(pos1==0) len1=inf; else len1=now-pos1; if(pos2==inf) len2=inf; else len2=pos2-now; if(len1>len2){ now+=len2;num[now]--;dir=1;ans+=len2; if(num[now]==0) update(now,0,1,n+1,1); }else if(len1<len2){ now-=len1;num[now]--;dir=-1;ans+=len1; if(num[now]==0) update(now,0,1,n+1,1); }else{ ans+=len1; if(dir==1){ now+=len2;num[now]--;dir=1; if(num[now]==0) update(now,0,1,n+1,1); }else{ now-=len1;num[now]--;dir=-1; if(num[now]==0) update(now,0,1,n+1,1); } } } } } printf("Case %d: %d\n",cas++,ans); } return 0; }
标签:
原文地址:http://blog.csdn.net/dan__ge/article/details/51916852