拓扑排序方法如下:
(1)从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它.
(2)从网中删去该顶点,并且删去从该顶点发出的全部有向边.
(3)重复上述两步,直到剩余的网中不再存在没有前驱的顶点为止.
这个题是标准的拓扑排序,但需注意这句话:where xxx is the number of relations processed at
the time either a sorted sequence is determined or an inconsistency is found, whichever
comes first, 也就是说一旦可以确定顺序或者出现环,就要立即输出
鄙人对于拓扑排序算法还不太理解,先奉上源代码(从网上找的),有时间再研究
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int g[26][26],degree[26],degreeR[26],path[26];
int ring,more;
int n,m;
int main(){
int i,j,k,t;
char u,v;
int ele;
int sure;
while(scanf("%d%d",&n,&m),n|m){
memset(g,0,sizeof(g));
memset(degreeR,0,sizeof(degreeR));
sure = 0;
for(getchar(),i=0;i<m;i++){
scanf("%c<%c",&u,&v);getchar();
g[ u-'A' ][ v-'A' ]=1;
degreeR[ v-'A' ]++;
stack<int> _sta;
for(j=0;j<n;j++) if( degreeR[j] == 0 ) _sta.push(j);
for(j=0;j<n;j++) degree[j]=degreeR[j];
more=0;
ring=0;
for(j=0;j<n;j++){
if( _sta.size()>1 ) more=1;
if( _sta.empty() ){ ring=1; break; }
ele = _sta.top(); _sta.pop();
path[j]=ele;
for(k=0;k<n;k++){
if( g[ele][k]!=0 && --degree[k] == 0 ) { _sta.push(k); }
}
}
if( j == n && more == 0){
printf("Sorted sequence determined after %d relations: ",i+1);
for(j=0;j<n;j++) printf("%c",'A'+path[j]); printf(".\n");
sure=true;
break;
}
else if( ring == 1 ){ printf("Inconsistency found after %d relations.\n",i+1);
sure=true; break; }
}
if( sure == 0 ) printf("Sorted sequence cannot be determined.\n");
for(t=i+1;t<m;t++){ scanf("%c<%c",&u,&v); getchar(); }
}
return 0;
}
浙公网安备 33010602011771号