【BestCoder Round #25】A(拓扑排序,找环)

来源:互联网 发布:python pack 编辑:程序博客网 时间:2024/04/27 13:32

题意不难看出是一道简单拓扑题目,自己对于拓扑一直没能掌握。这边就不写思路了,直接上代码了。

我的代码:

#include<iostream>#include<cstdio>#include<cstring>using namespace std;bool DIS[110][110];int r[110];bool vis[110];int main(){int n, m;while (cin >> n >> m){int a, b;memset(r, 0, sizeof(r));memset(DIS, 0, sizeof(DIS));memset(vis, 0, sizeof(vis));for (int i = 0; i < m; i++){scanf("%d%d", &b, &a);if (DIS[a][b] == 0){DIS[a][b] = 1;r[b]++;}}if (n == 1){cout << "NO" << endl;continue;}int counts = 0;while (counts < n){int mid=-1;int i;for (i = 1; i <=n;i++)if (r[i] == 0&&!vis[i]){mid = i;vis[i] = 1;break;}if (mid==-1)break;for (int i = 1; i <= n;i++)if (DIS[mid][i])r[i]--;counts++;}if (counts == n)cout << "YES" << endl;elsecout << "NO" << endl;}}

别人的代码(比较规范的拓扑):

#include<iostream>#include<cstdio>#include<vector>#include<cstring>#include<queue>using namespace std;int main(){int r[110];int n, m;while (cin >> n >> m){int a, b;vector<int>g[110];memset(r, 0, sizeof(r));for (int i = 0; i < m; i++){scanf("%d%d", &a, &b);g[b].push_back(a);r[a]++;}queue<int> q;for (int i = 1; i <= n;i++)if (r[i] == 0)q.push(i);int counts = 0;while (!q.empty()){int k = q.front();q.pop();for (int i = 0; i < g[k].size(); i++){int v = g[k][i];r[v]--;if (r[v] == 0)q.push(v);}counts++;}cout << (counts == n ? "YES":"NO")<< endl;}}



0 0