FZU 2163 多米诺骨牌(单调栈)

题目链接: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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值