题目链接
运用运算符重载的优先队列
Sample Input
2
2
1 5
2 4
2
1 5
6 6
Sample Output
11
12
题目意思不太好理解
可以看做一条直线,从坐标0出发,然后会遇到石头,看遇到石头的次数是奇数还是偶数
如果是偶数,就不动这块石头
如果是奇数,就扔这块石头
如果一个位置有多块石头 那么会先遇到重的石头(也就是能扔的距离更近的石头)
输入:
第一行是有多少组数据 第二行是该组数据有几块石头
每块石头给出2个数据 第一个数据是该石头的位置 第二个数据是该石头能扔多远
对于第一组数据
从0出发 走到1时第一次遇到石头 扔到6(1+5)
继续走 走到2时第二次遇到石头(偶数不扔)
继续走 走到6时第三次遇到石头 扔到11(6+5)
继续走 走到11时第四次遇到石头(偶数不扔)
思路:
可以重载运算符运用优先队列,将较近的石头放在队首
如果遇到队首的石头时是偶数,直接出队
如果遇到队首的石头是奇数,将扔后的石头入队,队首的石头出队
注意:
1.
重载运算符要重载小于号 <
优先队列比较的符号是 < 如果重载 > 会报错
2.
重载运算符的参数必须要加const
如果不加会报错
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
AC代码
#include <iostream>
#include <queue>
using namespace std;
class Node
{
public:
long long pos;
long long dis;
friend bool operator < (const Node &a,const Node &b)
{
if(a.pos == b.pos)
{
return a.dis > b.dis;
}
return a.pos > b.pos;
}
};
int main()
{
int line,n;
bool sign=1;
priority_queue<Node> que;
Node node;
cin >> line;
while(line--)
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> node.pos >> node.dis;
que.push(node);
}
while(!que.empty())
{
node = que.top();
if(sign) //扔
{
node.pos = que.top().pos + que.top().dis;
que.pop();
que.push(node);
sign = 0;
}
else //不扔
{
que.pop();
sign = 1;
}
}
cout << node.pos << endl;
}
return 0;
}