Description
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.
Input
The 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.
Output
Output the total distance Holedox will move. Holedox don’t need to return to the position 0.
Sample Input
Sample Output
#include <stdio.h>
int 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+=y1-x;
x=y1;
a[y1]--;
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: %d\n",c,s);
}
return 0;
}