poj 1094 Sorting It All Out(拓扑排序)
生活随笔
收集整理的這篇文章主要介紹了
poj 1094 Sorting It All Out(拓扑排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2018-3-25
拓撲排序的題目,需要注意的是,這里是邊輸入邊判斷的,之前有一組數據一直不知道為什么不過:
A>F B>D C>E F>D D>E E>F其實當最后一個加進去的時候,應該是出現回路的,而且題目要求我們先判斷回路再判斷是否解不唯一。
#include<iostream> #include<cstdio> #include<cstring> using namespace std;const int N = 26; bool x[N+1][N+1]; int in[N+1],tmp[N+1]; char res[N+1]; int m,n; int topoSort(){int i,j,s,point,cnt=0,f=1;for (i=1;i<=n;i++){tmp[i]=in[i];}for (i=1;i<=n;i++){s=0;for (j=1;j<=n;j++){if (!tmp[j]){s++;point=j;} }if (s==0) return 0;if (s>1) f=-1;tmp[point]=-1;res[cnt++]=point;for (j=1;j<=n;j++){if (x[point][j]) tmp[j]--;} }return f; }int main(){int i,j,p,q;char a,b,ch[4];bool flag;while (cin>>n>>m){if (m==0&&n==0) break;memset(x,0,sizeof(x));memset(in,0,sizeof(in));flag=0;for (i=1;i<=m;i++){scanf ("%s",ch);a=ch[0];b=ch[2];if (flag) continue;p=a-'A'+1;q=b-'A'+1;x[p][q]=1;in[q]++;p=topoSort();if (p==0){printf("Inconsistency found after %d relations.\n",i);flag=1;}else if (p==1){printf("Sorted sequence determined after %d relations: ",i);for(j=0;j<n;j++){printf("%c",res[j]+'A'-1);}printf(".\n");flag=1;}}if (!flag){printf("Sorted sequence cannot be determined.\n");}}return 0; }在topoSort函數里面,當s>1的時候,不應該立刻返回多解,而是要繼續執行,當把A,B,C對應的字母的入度都減一的時候我們會發現其實該圖是存在回路的。
總結
以上是生活随笔為你收集整理的poj 1094 Sorting It All Out(拓扑排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cmd命令大全 DOS窗口命令
- 下一篇: 权限问题导致zabbix无法监控mysq