/* Name: 拓扑排序,多次拓扑 Copyright: Author: Try86 Date: 16/04/12 21:36 Description: */ #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; const int N = 27; bool ch[N]; char ans[N]; //存拓扑序 int inDeg[N]; //入度数 struct node { int v; node *next; node(int vv, node *p) { v = vv; next = p; } }; struct graph { node *link; }G[N]; void init(int n) { for (int i=0; i<n; ++i) G[i].link = NULL; return ; } void buildG(int u, int v) { node *p = new node(v, G[u].link); G[u].link = p; return ; } int topoSort(int n, int s) { int temp[27], cs, j, k = 0; for (int i=0; i<n; ++i) temp[i] = inDeg[i];//当前各点入度数 bool flag = true; while (s--) { cs = 0;//统计入度为0的顶点个数 for (int i=0; i<n; ++i) { if (temp[i] == 0) j = i, ++cs; } if (cs >= 1) { if (cs > 1) flag = false;//入度为0的顶点个数大于1,拓扑序有多个,不能比较拓扑序的关系 for (node *p=G[j].link; p; p=p->next) --temp[p->v]; ans[k++] = j + 'A'; temp[j] = -1; ans[k] = '\0'; } else return -1;//入度为0的个数为0,存在回路,不能形成拓扑序 } if (flag) return k; return 0; } void del(node *p) { if (!p) return ; del(p->next); delete p; return ; } int main() { int n, m; char str[4]; while (scanf("%d%d", &n, &m) && n+m) { init(n); memset(ch, false, sizeof(ch)); memset(inDeg, 0, sizeof(inDeg)); int junge, counts, k; junge = counts = 0; for (int i=0; i<m; ++i) { scanf ("%s", str); if (junge != -1) {//junge!=-1,则当前输入下,不存在回路 int u = str[0] - 'A'; int v = str[2] - 'A'; buildG(u, v); ++inDeg[v]; if (!ch[u]) ++counts, ch[u] = true; if (!ch[v]) ++counts, ch[v] = true; } if (junge == 0) {//junge==0,则当前输入下,不存在回路,也不存在孤立点,图连通,需继续拓扑 int t = topoSort(n, counts); if (t == -1) junge = -1, k = i + 1; else if (t == n) junge = 1, k = i + 1; } } if (junge == -1) printf ("Inconsistency found after %d relations.\n", k); else if (junge == 0) printf ("Sorted sequence cannot be determined.\n"); else printf ("Sorted sequence determined after %d relations: %s.\n", k, ans); for (int i=0; i<n; ++i) del(G[i].link); } return 0; }