洛谷 P1823 [COI2007] Patrik 音乐会的等待

目录:


题目:

传送门


分析:

80分:

按照普通的单调栈的做法,每加入一个人,就开始操作:当当前栈顶小于这个人的身高时,那么就对答案进行累加,并且弹出栈顶。最后加入这个人。
但为了方便,我们就将与我们自己相同的都弹出,这样就可以更为方便的查看是否有比我高一级的,当确认完后,再把相同的和自己都加入到栈中就好了。

x=read();t=1;
while(s.size()>0&&x>=s.top())
{
   if(s.top()==x) t++;
   ans++;
   s.pop();
}
if(s.size()>0) ans++;

100分(AC):

其实也没什么就是用一个 pair p a i r 一维数组模拟栈, pair p a i r first f i r s t 位置存放身高, pair p a i r second s e c o n d 位置存放 first f i r s t 身高的人数,然后再按照 80 80 分的方法去做,就可以优化掉相同身高的时间,从而减少时间复杂度。


最后给大家提个醒,就是结果要用 long l o n g long l o n g ( int64 i n t 64 )保存,不然就会 WA W A 三个超级数据


代码:

80分:

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<deque>
#include<stack>
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}   
int ans=0;
stack<int> s;
int x;
int main()
{
    int n=read(),t;
    for(int i=1;i<=n;i++)
    {
        x=read();t=1;
        while(s.size()>0&&x>=s.top())
          {
            if(s.top()==x) t++;
            ans++;
            s.pop();
          }
        if(s.size()>0) ans++;
        for(int j=1;j<=t;j++) s.push(x);
    }
    printf("%d",ans);
    return 0;
}

100分(AC)

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<deque>
#include<stack>
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
long long ans;
int x,n,top=0;
pair<int,int>s[500001];
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
    {
        x=read();
        while(top&&x>s[top].first) 
          ans+=s[top--].second;
        if(x==s[top].first)
        {
            if(top>1) ans++;
            ans+=s[top].second++;
        }
        else
        {
            if(top) ans++;
            s[++top]=make_pair(x,1);
        }
    }
    printf("%lld",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值