标签:hdu4857
1 5 10 3 5 1 4 2 5 1 2 3 4 1 4 2 3 1 5 3 5 1 2
1 2 3 4 5
input: 1 3 1 3 1 answer: 3 1 2 而不是 2 3 1
WA代码:正序拓扑
#include <cstdio> #include <cstring> #include <queue> #define maxn 100002 using namespace std; int head[maxn], indegree[maxn], ans[maxn]; struct Node{ int to, next; } map[maxn]; void topoSort(int n) { priority_queue<int, vector<int>, greater<int> > Q; int i, u, id = 1; for(i = 1; i <= n; ++i) if(!indegree[i]) Q.push(i); while(!Q.empty()){ ans[id++] = u = Q.top(); Q.pop(); for(i = head[u]; i != -1; i = map[i].next) if(!--indegree[map[i].to]) Q.push(map[i].to); } for(i = 1; i <= n; ++i) if(i != n) printf("%d ", ans[i]); else printf("%d\n", ans[i]); } int main() { int t, n, m, a, b, i; scanf("%d", &t); while(t--){ memset(indegree, 0, sizeof(indegree)); memset(head, -1, sizeof(head)); scanf("%d%d", &n, &m); for(i = 0; i < m; ++i){ scanf("%d%d", &a, &b); map[i].to = b; map[i].next = head[a]; head[a] = i; ++indegree[b]; } topoSort(n); } return 0; }
#include <cstdio> #include <cstring> #include <queue> #define maxn 100002 using namespace std; int head[maxn], indegree[maxn], ans[maxn]; struct Node{ int to, next; } map[maxn]; void topoSort(int n) { priority_queue<int> Q; int i, u, id = 1; for(i = 1; i <= n; ++i) if(!indegree[i]) Q.push(i); while(!Q.empty()){ ans[id++] = u = Q.top(); Q.pop(); for(i = head[u]; i != -1; i = map[i].next) if(!--indegree[map[i].to]) Q.push(map[i].to); } for(i = n; i >= 1; --i) if(i != 1) printf("%d ", ans[i]); else printf("%d\n", ans[i]); } int main() { int t, n, m, a, b, i; scanf("%d", &t); while(t--){ memset(indegree, 0, sizeof(indegree)); memset(head, -1, sizeof(head)); scanf("%d%d", &n, &m); for(i = 0; i < m; ++i){ scanf("%d%d", &a, &b); map[i].to = a; map[i].next = head[b]; head[b] = i; ++indegree[a]; } topoSort(n); } return 0; }
HDU4857 逃生 【拓扑排序】,布布扣,bubuko.com
标签:hdu4857
原文地址:http://blog.csdn.net/chang_mu/article/details/38326143