Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 883 Accepted Submission(s): 307
Total Submission(s): 883 Accepted Submission(s): 307
Problem 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.
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
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
平心而论,这道题真心不难,需要注意的是每次查找离小熊最近的位置,这里可以用二分来做,还有就是方向的控制,,,,我用set水过,,,
AC代码:
#include<iostream>
#include<set>
#include<cmath>
#include<string.h>
#include<string>
#include<algorithm>
#define N 100005
using namespace std;
int num[N];
int main()
{
int T;
scanf("%d",&T);
for(int k=1;k<=T;++k)
{
memset(num,0,sizeof(num));
int n,m;
scanf("%d%d",&n,&m);
multiset<int>Q;
multiset<int>::iterator it,del;
__int64 sum=0;
int pre=0,cur=0,p;//标记当前位置和前一个位置
for(int i=0;i!=m;++i)
{
int a;
scanf("%d",&a);
if(!a)
{
int b;
scanf("%d",&b);
Q.insert(b);
num[b]++;
}
else
{
if(!Q.size()) continue;
int minx=0xffffff;
for(it=Q.begin();it!=Q.end();++it)
if(abs(*it-cur)<minx)
{
minx=abs(*it-cur);
del=it;
p=*it;
}
else if((*it-cur)==minx&&abs(*it-cur)*(cur-pre)>0)
{
minx=abs(*it-cur);
del=it;
p=*it;
}
Q.erase(del);
sum+=minx;
pre=cur;
cur=p;
}
}
printf("Case %d: %I64d\n",k,sum);
}return 0;
}