2015
05-23

# Holedox Eating

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.

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.

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.

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

Case 1: 9
Case 2: 4
Case 3: 2

#include<stdio.h>
#include<string.h>
#define N 100000
#define INF 100000020
#define lowbit(x) ((x)&(-(x)))

int a[N*2];
int L;
{
while(t<=L)
{
a[t]+=v;
t=(t|(t-1))+1;
}
}

long long query(int t)
{
long long ans=0;
while(t>0)
{
ans+=a[t];
t&=t-1;
}
return ans;
}

int right_search(int t)
{
if(t==L)
{
if(query(L)-query(L-1))
return L;
return INF;
}
int l=t,r=L;
int cmp=query(t-1);
while(l<=r)
{
int mid=(l+r)>>1;
query(mid)-cmp>0?(r=mid-1):(l=mid+1);
}
if(query(l)-cmp==0)
return INF;
return l;
}

int left_search(int t)
{
if(t==1)
{
if(query(1))
return 1;
else return INF;
}
int l=1,r=t;
int cmp=query(t);
int mid;
while(l<=r)
{
mid=(l+r)>>1;
cmp-query(mid)>0?(l=mid+1):(r=mid-1);
}
if(query(l)==0)
return INF;
return l;
}

int main(void)
{
int t,n,ct=0,dist,pos,dir,x;
scanf("%d",&t);
while(t--)
{
pos=1;
dist=0;
dir=1;
memset(a,0,sizeof(a));
scanf("%d%d",&L,&n);
L++;
while(n--)
{
scanf("%d",&x);
if(x)
{
int l=left_search(pos);
int r=right_search(pos);
if(l==INF&&r==INF)
;
else  if(pos-l>r-pos||l==INF)
{
dist+=r-pos;
pos=r;
dir=1;
}
else if(pos-l<r-pos||r==INF)
{
dist+=pos-l;
pos=l;
dir=-1;
}
else if(dir==1)
{
dist+=r-pos;
pos=r;
}
else
{
dist+=pos-l;
pos=l;
}