Thinking in topological sort
how to judge if has a loop
when there are still some unvisited node, but the number of node whose in-degree==0 equals zero, we can say: there is a loop in the graph.
(因为拓扑排序是一个节点一个节点的去排除,当有未排除的节点时,并且没有入读不为0的节点,那么就一定有环存在)
how to judge if has isolated node or is the top-order not exclusive
when the are still some unvisited nodes, but the number of node whose in-degree == 0 greater than one, we can say the order is uncertain.
talk is cheap, show me the code.
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <cstring>
#include <cstdio>
#include <map>
#include <assert.h>
using namespace std;
const int MAXSIZE = 30;
int road[MAXSIZE][MAXSIZE];
int indegree[MAXSIZE];
int visit[MAXSIZE];
int temp[MAXSIZE];
int n,m;
string string1;
int topsort() {
memset(visit, 0, sizeof(visit));
memcpy(temp, indegree, sizeof(indegree));
string1 = "";
int flag = 1;
for (int i = 0; i < n; ++i) {
int m = 0, u = -1;
for (int j = 0; j < n; ++j) {
if (!visit[j] && temp[j] == 0) {
u = j, m++;
}
}
if (m == 0) return 0; //有环路
if (m > 1) flag = -1; //无序
visit[u] = 1;
string1 += (u+'A');
for (int j = 0; j < n; ++j) {
if (!visit[j] && road[u][j])
temp[j]--;
}
}
return flag;
}
int main(){
// freopen("../in.txt", "r", stdin);
while (scanf("%d %d", &n, &m)&&n){
memset(road, 0, sizeof(road));
memset(indegree, 0, sizeof(indegree));
char a,op,b;
bool isok = false;
for (int k = 0; k < m; ++k) {
cin>>a>>op>>b;
road[a-'A'][b-'A'] = 1;
if (isok) continue;
//入度
memset(indegree,0, sizeof(indegree));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
indegree[j]+= road[i][j];
}
}
int res = topsort();
if (res == 0){
cout<<"Inconsistency found after "<<k+1<<" relations."<<endl;
isok = true;
} else if (res == 1){
cout<<"Sorted sequence determined after "<<k+1<<" relations: "<<string1<<"."<<endl;
isok = true;
}
}
if (!isok)
cout<<"Sorted sequence cannot be determined."<<endl;
}
}
Reference
https://www.cnblogs.com/yueshuqiao/archive/2011/08/16/2140485.html