暴力模拟,用优先队列来存当前位置的最近左右,取的时候加判断即可。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
typedef __int64 ll;
#define N 100005
priority_queue <int, vector<int>, greater<int> > q2; //left
priority_queue <int, vector<int>, less<int> > q1; //right
//int a[N*2];
int main()
{
int tot;
int t = 1;
for ( scanf("%d", &tot); tot--; )
{
int l, n;
scanf("%d%d", &l, &n);
while( !q1.empty() )
q1.pop();
while( !q2.empty() )
q2.pop();
int now = 0, x, c;
int cnt = 0;
ll ans = 0;
int dir = 1; //1 -> right
while(n--)
{
scanf("%d", &c);
if ( c == 0 )
{
scanf("%d", &x);
if( x > now )
q2.push(x);
else
q1.push(x);
}
else
{
if( !q1.empty() && !q2.empty() )
{
int x = q1.top();
int y = q2.top();
if ( abs(x - now) > abs(y - now) )
{
if( !dir )
dir = 1;
ans += abs(now - y);
now = y;
q2.pop();
}
else if( abs(x - now) < abs(y - now) )
{
if( dir )
dir = 0;
ans += abs(x - now);
now = x;
q1.pop();
}
else
{
ans += abs(x - now);
if( dir )
now = y, q2.pop();
else
now = x, q1.pop();
}
}
else
{
if( q1.empty() && q2.empty() )
continue;
if( !q1.empty() )
{
int x = q1.top();
q1.pop();
if( dir )
dir = 1;
ans += abs(now - x);
now = x;
}
if( !q2.empty() )
{
int y = q2.top();
q2.pop();
if( !dir )
dir = 1;
ans += abs(now - y);
now = y;
}
}
}
//printf("ans: %I64d\n", ans);
}
printf("Case %d: ", t++);
printf("%I64d\n", ans);
}
return 0;
}