HDU1896 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<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 integersPi(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
题解:
此题题意理解问题不大,即向一个方向走,遇到第奇数个石头就扔出去,遇到第偶数个就不用管,注意是第偶数个,与同一个位置的石头个数无关。
当同一个位置有多个石头时,优先扔出可以扔的距离最近的石头。
AC代码:
#include<stdio.h>
#include<vector>
#include<queue>
int ans;
using namespace std;
struct stone{//创造stone结构体,记录石头的初始位置,和扔的距离
int p,d;
}stones;
struct change{//比较的规则
bool operator() (const stone &s1,const stone &s2)
{
if(s1.p!=s2.p)
return s1.p>s2.p;
return s1.d>s2.d;
}
};
/*
struct stone{
int a, b;
bool friend operator < (stone x,stone y) {//这里重载小于运算符(即重新定义小于的运算规则)
if(x.a != y.a) {
return x.a > y.a;
}
return x.b > y.b;
}
}stones;
priority_queue<stone> q;//建立优先队列
//这是重载运算符的另一种方法,详细见下文。
*/
priority_queue<stone ,vector<stone>,change> q;//建立优先队列
int main(){
int T,N;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d%d",&stones.p,&stones.d);
q.push(stones);//每次压进去都会按重载的规则排序
}
int j=1;
while(!q.empty()){
stones=q.top();
q.pop();
if(j%2==0)
{
j++;
continue;
}
else
{
stones.p+=stones.d;
q.push(stones);
ans=stones.p;
j++;
}
}
printf("%d\n",ans);
}
}
题中所学:
1、优先队列:
这里用到的是对结构体的排序,并自定义队列排序比较规则。可以重载运算符后按默认格式创建优先队列, 也可以定义排序的方法。
2、重载运算符:
对运算符重新定义 重载运算符