Bus of Characters CodeForces - 982B(思维题 栈)

Bus of Characters

  CodeForces - 982B 

题意:公交车上有n排座位编号为1-n,每排有两个座位,奇怪的是,这些座位的宽度是完全不一样的,现在有2×n个人有顺序的上车,其中有n个内向的人,n个外向的人。每个内向的人只能和外向的人坐在一起。内向的人上车后,会选择没有人的,且座位宽度小的座位坐下,而外向的人会选择有人的,座位宽度大的座位坐下,现给出一个长为2×n的01串,0表示内向的人,1表示外向的人,输出每个人坐位的排号。

思路:水题,把宽度按从小到大排序,如果是内向的人的话,直接坐最小的座位,并把这个位置入栈,如果是外向的,就直接出栈即可。

因为后入栈的一定比先入栈的座位宽度要大,所以这样做是可行的!

#include "iostream"
#include "algorithm"
#include "cstdio"
#include "stack"
using  namespace std;
typedef pair<int,int> P;
P man[200005];
bool cmp(P a,P b)
{
    return a.first<b.first;
}
int main()
{
    int n,t=1;
    char x;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&man[i].first);
        man[i].second=i;
    }
    getchar();
    sort(man+1,man+1+n,cmp);
    stack<P> s;
    if(!s.empty()) s.pop();
    for(int i=1;i<=2*n;i++){
        scanf("%c",&x);
        if(x=='0'){
            printf("%d",man[t].second);
            s.push(man[t]);
            t++;
        }
        else{
            P m=s.top();
            s.pop();
            printf("%d",m.second);
        }
        if(i!=2*n)
            printf(" ");
        else
            printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41874469/article/details/80474296