HDU - 1896

Stones

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

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


題目大意
有個叫Sempr的同學走路的時候覺得無聊,就丟石子玩…他會把遇到的第奇數個石子往前扔,而忽略遇到的第偶數個棋子。(如果有多個石子在同一個位置,那麼視作先遇到扔的近的。)

那麼現在給出路上的石子總數,以及每個石子的初始位置與這個石子能扔的距離,試求石子能達到的最遠距離。

解題思路
模擬Sempr同學扔石子的全過程。對於每個石子來說,都需要記錄兩個信息:1.當前位置 2.能扔的距離。因此採用一個結構體表示,同時用一個優先隊列priority_queue表示Sempr同學還能遇到的石子,越先遇到的優先級越高。
我們會發現如果有n個石子,整個過程可看做n-1次 撿起石子丟出去,路過下一個。最後再做一次丟出,此時就得到了最遠距離。
其中注意一下 優先隊列的判定方式 不要寫錯即可。



源代碼

#include<iostream>
#include<stdio.h>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

int times, num;
struct Node {
    int pos;
    int dis;
    friend bool operator < (Node a, Node b){
        if (a.pos == b.pos)
            return a.dis > b.dis;
        else
            return a.pos > b.pos;
    }

};
priority_queue<Node> q;
Node temp;

int main() {
    scanf("%d", &times);
    int i;
    for (int ti = 0; ti < times; ti++) {
        scanf("%d", &num);
        for (i = 0; i < num; i++) {
            scanf("%d%d", &temp.pos, &temp.dis);
            q.push(temp);
        }
        for(i=0;i<num-1;i++){
            temp = q.top(); 
            temp.pos = temp.pos + temp.dis;
            q.push(temp);   
            q.pop();        
            q.pop();
        }
        temp = q.top();
        printf("%d\n", temp.pos + temp.dis);
        q.pop();
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章