hdu 4302 优先队列

时间:2022-06-14 19:00:34

进一步学习了优先队列的用法

题意:一只小动物在直线上走,起始位置为零,之后会出现食物,动物要去距离自己最短的食物那,若两边的食物距离相等,则选择之前走的方向的食物

0 x,代表x的位置出现了食物,1代表去吃一个食物

 #include<stdio.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
struct cmp
{
bool operator()(int x,int y)
{
return x>y;
}
};
priority_queue<int,vector<int>,cmp>q;
priority_queue<int>q2;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int T;
int L,n;
int A,B;
int iCase=;
scanf("%d",&T);
while(T--)
{
iCase++;
scanf("%d%d",&L,&n);
while(!q.empty())q.pop();
while(!q2.empty())q2.pop();
int x=;
int ans=;
int t=;
while(n--)
{
scanf("%d",&A);
if(A==)
{
scanf("%d",&B);
if(B>=x)q.push(B); //记录右边的点
else q2.push(B); //记录左边的点
}
else
{
if(!q.empty()&&!q2.empty())
{
int temp1=q.top();
int temp2=q2.top();
if(temp1-x<x-temp2)
{
t=;
ans+=q.top()-x;
x=q.top();
q.pop();
}
else if(temp1-x>x-temp2)
{
t=-;
ans+=x-q2.top();
x=q2.top();
q2.pop();
}
else if(t==)
{
ans+=q.top()-x;
x=q.top();
q.pop();
}
else
{
ans+=x-q2.top();
x=q2.top();
q2.pop();
}
}
else if(!q.empty())
{
t=;
ans+=q.top()-x;
x=q.top();
q.pop();
}
else if(!q2.empty())
{
t=-;
ans+=x-q2.top();
x=q2.top();
q2.pop();
}
} }
printf("Case %d: %d\n",iCase,ans);
}
return ;
}