poj1094Sorting It All Out(拓撲排序)

來源:互聯網
上載者:User

這題挺奇怪的,我之前還真麼做過這樣的拓撲排序,之前卡了一陣子,這個題目是判斷到第幾個成環,到第幾個正好能唯一排序,另一種就是怎麼也排不了序,就是每個資料跑一遍拓撲排序就行了

#include <iostream>#include <queue>#include <string.h>#include <stdio.h>using namespace std;const int maxn=30;int head[maxn],ip,indegree[maxn];int n,m,seq[maxn];struct note{    int v,next;}edge[maxn*maxn];void init(){    memset(head,-1,sizeof(head));    memset(indegree,0,sizeof(indegree));    memset(seq,0,sizeof(seq));    ip=0;}void addedge(int u,int v){    edge[ip].v=v;    edge[ip].next=head[u];    head[u]=ip++;}int topo(){    queue<int>q;    int indeg[maxn];    for(int i=0;i<n;i++)    {        indeg[i]=indegree[i];        if(indeg[i]==0)            q.push(i);    }    int k=0;    bool res=false;    while(!q.empty())    {        if(q.size()!=1)            res=true;        int u=q.front();        q.pop();        seq[k++]=u;        for(int i=head[u];i!=-1;i=edge[i].next)        {            int v=edge[i].v;            indeg[v]--;            if(indeg[v]==0)                q.push(v);        }    }    if(k<n) return -1;//成環    if(res)        return 0;//多解    return 1;//唯一解}int main(){   while(cin>>n>>m)   {       init();      int sign=0;       if(n==0&&m==0)        break;       int flag=0;       for(int i=0;i<m;i++)       {           char s1,s2,s3;           cin>>s1>>s2>>s3;           if(sign==1)//如果輸出過了,對後面的資料就跳過就行了            continue;           int u=s1-'A';           int v=s3-'A';            sign=0;           addedge(u,v);           indegree[v]++;//這塊千萬別忘了            flag=topo();           if(flag==-1)           {               sign=1;               cout<<"Inconsistency found after "<<i+1<<" relations."<<endl;           }           else if(flag==1)           {               sign=1;               //cout<<i<<endl;               cout<<"Sorted sequence determined after "<<i+1<<" relations: ";               for(int j=0;j<n;j++)//這裡一定是小於n,不能是小於i,要保證個數                    putchar(seq[j]+'A');//這塊注意,用putchar輸出字元               cout<<"."<<endl;           }           else           {               continue;           }       }       if(sign==0)        cout<<"Sorted sequence cannot be determined."<<endl;   }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.