HDU 1896 Stones [priority queue]

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

题目大意:有个人在放学回家的路上乐(xian)此(de)不(dan)疲(teng)的玩一个扔石头游戏。如果是奇数次碰到石头就把石头扔出去,偶数次碰到的话就不管它。如果在同一点有多个石头,选择扔可以扔最远的那块。问最远的石头离原点的距离。(因为偶数次碰到不扔,所以会有终点)

大致思路:本题用优先队列进行处理,在优先队列中,用石头的位置作为优先级标准进行排序,如果遇到石头的次数是奇数次则将石头扔出去,并更新该石头的位置,并将原先的位置踢出队列,形成新的优先队列。如果是偶数,则直接将石头踢出队列即可。详见代码。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
using namespace std;
struct stone//定义一个结构体 x表示石头位置,y表示石头被扔的距离
{
    int x,y;
};
bool operator < (stone a,stone b)//优先队列需要被重载为大的在队顶
{
    if(a.x==b.x)
        return a.y>b.y;
    else return a.x>b.x;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int i,n;
        priority_queue<stone> q;
        cin>>n;
        stone t;
        for(i=0;i<n;i++)
        {
            cin>>t.x>>t.y;
            q.push(t);//入队
        }
        int flag=1;//判断第几次碰到石头
        while(!q.empty())//没有石头扔的时候,队列即是空的
        {
            t=q.top();//取队顶的石头位置
            q.pop();//原先的位置出队
            if(flag%2==1)
            {
                t.x=t.x+t.y;
                q.push(t);//更新完的石头位置入队
            }
            flag++;
        }
        cout<<t.x<<endl;
    }
    return 0;
}

 

 

posted on 2017-08-02 23:57  FTA_Macro  阅读(133)  评论(0编辑  收藏  举报

导航