码迷,mamicode.com
首页 > 编程语言 > 详细

nyoj Sorting It All Out (拓扑排序)

时间:2015-03-15 16:50:57      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

三种情况分别是:

1. 在某位置可以确定拓扑排序。

2. 在某位置出现了环

3. 到最后都不能确定拓扑排序(某一位置入度为0的点有多个),可以续输入执行下去。

 

每输入一组数据都要做一次判断

技术分享
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<vector>
 4 #include<queue>
 5 using namespace std;
 6 const int N = 105;
 7 int n, m, in[N], temp[N], ans[N], t, pos, num;
 8 char X, O, Y;
 9 vector<int>G[N];
10 queue<int>q;
11 
12 void init(){
13     memset(in, 0, sizeof(in));
14     for (int i = 0; i <= n; ++i){
15         G[i].clear();
16     }
17 }
18 
19 int topoSort(){
20     while (!q.empty())q.pop();
21     for (int i = 0; i<n; ++i)if (in[i] == 0){
22         q.push(i);
23     }
24     pos = 0;
25     bool unSure = false;
26     while (!q.empty()){
27         if (q.size()>1) unSure = true;
28         int t = q.front();
29         q.pop();
30         ans[pos++] = t;
31         for (int i = 0; i<G[t].size(); ++i){
32             if (--in[G[t][i]] == 0)
33                 q.push(G[t][i]);
34         }
35     }
36     if (pos<n) return 1;
37     if (unSure)  return 2;
38     return 3;
39 }
40 
41 int main(){
42     int x, y, i, flag, ok, stop;
43     while (~scanf("%d%d%*c", &n, &m),n+m){
44         init();
45         flag = 2;
46         ok = false;
47         for (i = 1; i <= m; ++i){
48             scanf("%c%c%c%*c", &X, &O, &Y);
49             if (ok) continue; 
50             x = X - A, y = Y - A;
51             if (O == <){
52                 G[y].push_back(x);
53                 ++in[x];
54             }
55             else if (O == >){
56                 G[x].push_back(y);
57                 ++in[y];
58             }
59             memcpy(temp, in, sizeof(in));
60             flag = topoSort();
61             memcpy(in, temp, sizeof(temp));
62             if (flag != 2){
63                 stop = i;
64                 ok = true;
65             }
66         }
67         if (flag == 3){
68             printf("Sorted sequence determined after %d relations: ", stop);
69             for (int i = pos - 1; i >= 0; --i)
70                 printf("%c", ans[i] + A);
71             printf(".\n");
72         }
73         else if (flag == 1){
74             printf("Inconsistency found after %d relations.\n", stop);
75         }
76         else{
77             printf("Sorted sequence cannot be determined.\n");
78         }
79     }
80     return 0;
81 }
代码君

 

nyoj Sorting It All Out (拓扑排序)

标签:

原文地址:http://www.cnblogs.com/usedrosee/p/4339957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!