拓撲排序

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int MAX_N=100005;
#define inf 1<<23
typedef long long ll;
typedef long long LL;
vector<int>c[10000+5];//從i出發
int r[10000+5];//i爲終點,計算入度
int res[10000+5];
bool tupo_stack(int n)//棧版
{
    memset(res,0,sizeof(res));
    stack<int>s;
    for(int i=0; i<n; i++)
    {
        if(!r[i])
        {
            s.push(i);
        }
    }
    int sum=0;//對輸出頂點記錄數目
    int k;
    while(!s.empty())
    {
        k=s.top();
        s.pop();
        res[sum++]=k;
        for(std::vector<int>::iterator i=c[k].begin(); i<c[k].end(); i++)
        {
            r[*i]--;
            if(!r[*i])
            {
                s.push(*i);
            }
        }
    }
    if(sum<n)
    {
        return false;
    }
    return true;
}
bool tupo_queue(int n)//隊列版
{
    memset(res,0,sizeof(res));
    queue<int>q;
    for(int i=0; i<n; i++)
    {
        if(!r[i])
        {
            q.push(i);
        }
    }
    int sum=0;//對輸出頂點記錄數目
    int k;
    while(!q.empty())
    {
        k=q.front();
        q.pop();
        res[sum++]=k;
        for(std::vector<int>::iterator i=c[k].begin(); i<c[k].end(); i++)
        {
            r[*i]--;
            if(!r[*i])
            {
                q.push(*i);
            }
        }
    }
    if(sum<n)
    {
        return false;
    }
    return true;
}
int main()
{


    int n;//頂點數目
    int m;//行數
    char a,b;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(r,0,sizeof(r));
        for(int i=0; i<m; i++)
        {
            // scanf("%c%c",&a,&b);//a指向b
            cin>>a>>b;
            c[(a-'A')].push_back(b-'A');
            r[(b-'A')]++;
        }
        if(tupo_queue(n))
        {
            for(int i=0; i<n; i++)
            {
                cout<<(char)(res[i]+'A')<<" ";
            }
            cout<<endl;
        }
        else
        {
            cout<<"ERROR"<<endl;
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章