题目链接:FZU 2163 多米诺骨牌
单调栈的题目写起来都差不多,想到了就很简单,而且有个共同特点是用VC交会TLE,G++还挺快的,可能是VC对STL的优化不够好?
一般来讲入栈时比较的是什么单调的就是什么,但是这个题感觉单调的东西有点说不清楚,只可意会不可言传==,还是对单调栈的理解不够吧。不过这个不要紧,做这类题目不需要考虑单调的是什么,只要清楚栈内元素什么时候出栈还有其他元素什么时候入栈就行了。
#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;
const int MAX_N = 100000 + 100;
struct Node
{
int i, r, l;
};
struct xAh
{
int x, h, i;
};
bool cmp(xAh a, xAh b)
{
return a.x < b.x;
}
xAh xh[MAX_N];
int ans[MAX_N];
int main()
{
//freopen("in.txt", "r", stdin);
int n;
while(scanf("%d", &n) != EOF)
{
stack <Node> S;
Node temp, tmp;
for(int i = 0; i < n; i++)
{
scanf("%d%d", &xh[i].x, &xh[i].h);
xh[i].i = i;
}
sort(xh, xh + n, cmp);
for(int i = 0; i < n; i++)
{
temp.i = xh[i].i, temp.l = i;
temp.r = xh[i].x + xh[i].h - 1;
while(!S.empty() && S.top().r < xh[i].x)
{
tmp = S.top();
S.pop();
ans[tmp.i] = i - tmp.l;
}
/*if(!S.empty() && (S.top().r - xh[i].x) > temp.r)
temp.r = S.top().r - xh[i].x;*/
S.push(temp);
}
while(!S.empty())
{
tmp = S.top();
S.pop();
ans[tmp.i] = n - tmp.l;
}
for(int i = 0; i < n - 1; i++)
printf("%d ", ans[i]);
printf("%d\n", ans[n - 1]);
}
return 0;
}