Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that.
Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1].
The first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point.
Print n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself).
4 16 5 20 5 10 10 18 2
3 1 4 1
4 0 10 1 5 9 10 15 10
4 1 2 1
栈这个数据结构真的很好用,对于一些递推类的题目,用栈处理会显得很清晰,容易理解. 以后有关于递推的题目要考虑栈这个神奇的东东了.
题意: 题目就是一个骨牌的游戏,从后往前递推就可以搞定了.
详细看下代码吧!
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stack>
using namespace std;
const int M = 1e5 + 5;
typedef pair<int , int > res;//定义一个向量,用来存放当前骨牌的位置和骨牌推倒的牌数
struct N
{
int x,h,id,num;
bool operator< (const N &a) const
{
return a.x > x;
}
}s[M];
bool cmp(N a, N b)
{
return a.id < b.id;
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d %d",&s[i].x,&s[i].h);
s[i].id = i + 1;
s[i].num = 1;
}
sort(s, s + n); //先对每个骨牌的位置从小到大排下序.
stack<res> ans; //用栈来处理,如果当前的骨牌可以推倒栈顶的骨牌,则栈顶的骨牌出栈;
for(int i = n - 1; i >= 0; i--) //从后往前递推;
{
if(i == n - 1) ans.push(make_pair(s[i].x, s[i].num));
else
{
int len = s[i].x + s[i].h - 1;
while(1)
{
res p = ans.top();
int tp = p.first;
if(tp >= s[i].x && tp <= len) //当前栈顶的骨牌在推倒的范围内,则出栈;
{
s[i].num += p.second;
ans.pop();
}
else break;
if(ans.empty()) break;
}
ans.push(make_pair(s[i].x,s[i].num));
}
}
sort(s, s + n, cmp);//处理完之后对id排下序,输出;
for(int i = 0; i < n; i++)
{
printf(i == n - 1 ? "%d\n" : "%d ", s[i].num);
}
return 0;
}