T628213 值轮兵团站岗

· · 个人记录

题目

T628213 值轮兵团站岗

错误原因:

不知代码怎么写

思路

1.定义变量

2.出栈

if(opt==1)
        {
            cin>>x;
            sum+=x;
            while(a[tail]+sum>k && tail-head+1>0)
            {
                tail--;
            }
        }

3.入栈

if(opt==2)
        {
            cin>>x;
            sum-=x;
            while(a[head]+sum<-k && tail-head+1>0)
            {
                head++;
            }
        }

4.数数还有多少人

if(opt==3)
        {
            cout<<tail-head+1<<endl;
        }

正确代码

#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5;
long long n,m,k,a[N],tail=-1,head;
long long sum,x,opt;
int main()
{
    cin>>n>>m>>k;
    for(int i=1;i<=n;i++)
    {
        cin>>a[++tail];
    }
    sort(a,a+n);
    while(m--)
    {
        cin>>opt;
        if(opt==1)
        {
            cin>>x;
            sum+=x;
            while(a[tail]+sum>k && tail-head+1>0)
            {
                tail--;
            }
        }
        if(opt==2)
        {
            cin>>x;
            sum-=x;
            while(a[head]+sum<-k && tail-head+1>0)
            {
                head++;
            }
        }
        if(opt==3)
        {
            cout<<tail-head+1<<endl;
        }
    }
    return 0;
}