士兵排队问题

拓扑排序+优先队列(考虑题目需要注意字符串排序的情况)

优先队列

递增 priority_queue <int,vector<int>,greater<int> > q;

递减 priority_queue <int,vector<int>,less<int> >q;

#include<bits/stdc++.h>
using namespace std;
const int maxn=100;
int in[maxn]= {0};
int f[maxn]= {0};
int ans[maxn]= {0};
vector <int> edge[maxn];
priority_queue< int,vector <int>,greater <int> >q;
int main()
{
    for(int i=1;i<100;i++) edge[i].clear();
    while(!q.empty()) q.pop();
    char a,b;
    int c=0,i,t=0,k;
    while(~scanf(" %c>%c",&a,&b))
    {
        if(f[a]==0)
            f[a]=1,c++;
        if(f[b]==0)
            f[b]=1,c++;
        in[b]++;
        edge[a].push_back(b);
    }
    for(i='A'; i<='Z'; i++)
        if(f[i]&&in[i]==0)
            q.push(i);
    while(!q.empty())
    {
        k=q.top();
        ans[t++]=k;
        q.pop();
        for(i=0; i<edge[k].size(); i++)
        {
            in[edge[k][i]]--;
            if(in[edge[k][i]]==0)
                q.push(edge[k][i]);
        }
    }
    if(t==c){
        for(i=0; i<t; i++)
            printf("%c",ans[i]);
    }
    else printf("No Answer!");
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41058467/article/details/80994799