首页 > 代码库 > HDU1896 优先队列2

HDU1896 优先队列2

D - 优先队列入门2
Time Limit:3000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 1896

Description

Because of the wrong status of the bicycle, Sempr begin to walk east to west every morning and walk back every evening. Walking may cause a little tired, so Sempr always play some games this time. 
There are many stones on the road, when he meet a stone, he will throw it ahead as far as possible if it is the odd stone he meet, or leave it where it was if it is the even stone. Now give you some informations about the stones on the road, you are to tell me the distance from the start point to the farthest stone after Sempr walk by. Please pay attention that if two or more stones stay at the same position, you will meet the larger one(the one with the smallest Di, as described in the Input) first. 
 

Input

In the first line, there is an Integer T(1<=T<=10), which means the test cases in the input file. Then followed by T test cases. 
For each test case, I will give you an Integer N(0<N<=100,000) in the first line, which means the number of stones on the road. Then followed by N lines and there are two integers Pi(0<=Pi<=100,000) and Di(0<=Di<=1,000) in the line, which means the position of the i-th stone and how far Sempr can throw it. 
 

Output

Just output one line for one test case, as described in the Description. 
 

Sample Input

2 2 1 5 2 4 2 1 5 6 6
 

Sample Output

11 12
 

还是优先队列问题,题目大意:路上有很多石头,当你遇到奇数序列的石头就把他向前仍,偶数的不动他,如果两个石头一起,先考虑可以仍的比较近的石头仍也就是比较大的石头,这样一直下去,直到前面所有的石头都不可以仍了为止。

其实就是将这个过程坐标化,Pi就是坐标,而Di就是有几个单位长度。

这里优先队列采用的还是自定义结构体的方法:

struct point
{
	int dis,pos;
	friend bool operator <(point a,point b)
	{
		if(a.pos==b.pos)
			return a.dis>b.dis;
		return a.pos>b.pos;
	}
};
同样,题目中有“如果两个石头一起,先考虑可以仍的比较近的石头仍也就是比较大的石头“,所以应该有if(a.pos==b.pos)  return a.dis>b.dis;

至于return 语句里面的‘<’和‘>’的判断,具体要这么用,这里可以有个简单总结记忆:

当是最大优先队列的时候,即用符号<作比较:

当是最小优先队列的时候,即用符号>作比较。

本题中距离和位置都是较小优先,所以两处return语句都用<;

全代码如下:

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

struct point
{
	int dis,pos;
	friend bool operator <(point a,point b)
	{
		if(a.pos==b.pos)
			return a.dis>b.dis;
		return a.pos>b.pos;
	}
}t;

int main()
{
	int i,n,m,p,d;
	scanf("%d",&m);
	priority_queue<point>q;
	while(m--)
	{
		scanf("%d",&n);
		while(!q.empty())
			q.pop();
		for(i=0;i<n;i++)
		{
			scanf("%d%d",&t.pos,&t.dis);
			q.push(t);
		}
		int ans=0,count=1;
		//point p;
		while(!q.empty())
		{
			if(count&1)
			{
				t=q.top();
				q.pop();
				t.pos+=t.dis;
				ans=t.pos;
				q.push(t);
			}
			else
				q.pop();
			count++;
		}
		printf("%d\n",q.top().pos);
	}
	return 0;
}