Holedox is a small animal which can be considered as one point. It lives in a straight pipe whose length is L. Holedox can only move along the pipe. Cakes may appear anywhere in the pipe, from time to time. When Holedox wants to eat cakes, it always goes to the nearest one and eats it. If there are many pieces of cake in different directions Holedox can choose, Holedox will choose one in the direction which is the direction of its last movement. If there are no cakes present, Holedox just stays where it is.
InputThe input consists of several test cases. The first line of the input contains a single integer T (1 <= T <= 10), the number of test cases, followed by the input data for each test case.The first line of each case contains two integers L,n(1<=L,n<=100000), representing the length of the pipe, and the number of events.
The next n lines, each line describes an event. 0 x(0<=x<=L, x is a integer) represents a piece of cake appears in the x position; 1 represent Holedox wants to eat a cake.
In each case, Holedox always starts off at the position 0.
OutputOutput the total distance Holedox will move. Holedox don’t need to return to the position 0.
Sample Input 3 10 8 0 1 0 5 1 0 2 0 0 1 1 1 10 7 0 1 0 5 1 0 2 0 0 1 1 10 8 0 1 0 1 0 5 1 0 2 0 0 1 1 Sample Output Case 1: 9 Case 2: 4 Case 3: 2 解析:注意每个位置上的食物量没有上限,然后我们每次寻找左右两边食物的位置,哪个近就去哪个,然后如果一样近就要判断上一次运动方向来决定去右边还是左边,我们每次运动用 f 来记录方向就好。#includeint a[100005]; //用来记录每个坐标点的食物数量 int main() { int t,l,q,s,x,f,z,i,s1,s2,y1,y2,p,c=0; scanf("%d",&t); while(t--){ c++; //测试用例编号 scanf("%d%d",&l,&q); for(i=0;i<=l;i++) a[i]=0; //初始化0 x=0,f=1,s=0; //x代表当前位置,f代表上一次方向(1为右,-1为左),s代表移动总距离 while(q--){ scanf("%d",&z); if(z==0){ scanf("%d",&p); a[p]++; //对应位置食物数量+1 }else{ s1=0,s2=0; //s1,s2代表主角 右边 左边 是否有食物 for(i=x;i<=l;i++){ //先寻找右边 if(a[i]>=1){ //如果有 y1=i; //y1记录当前食物位置 s1=1; //s1表示右边有食物 break; } } for(i=x-1;i>=0;i--){ //寻找左边 if(a[i]>=1){ y2=i; s2=1; break; } } if(s1*s2==0){ //相乘为0代表要么左右边都没食物,要么左边有,要么右边有 if(s1==1){ //右边有 s+=y1-x; //累加距离 a[y1]--; //该位置食物数量-1 x=y1; //更新当前主角位置 f=1; //方向为右 } else{ //左边有 s+=x-y2; x=y2; a[y2]--; f=-1; //方向为左 } }else{ //该类是两边都有的情况,要比较距离大小 if(y1-x x-y2){ //左边近 s+=x-y2; x=y2; a[y2]--; f=-1; }else{ //一样近,根据f的方向来判断去左边还是右边 if(f==1) s+=y1-x,x=y1,a[y1]--; else s+=x-y2,x=y2,a[y2]--; } } } } printf("Case %d: %dn",c,s); } return 0; }



