标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 688 Accepted Submission(s): 190
题目意思不用多说吧,陈立杰出的题,果然很不错,当天比赛BC过了的只有9个人。觉得是一道非常不错的拓扑排序题吧。
解题思路:因为既要满足一定的约束顺序,又要满足一定的优先顺序。反向建图,先把度为0且下标值大的输出到一个排序数组当中,然后再反向输出这个数组。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <queue> #define MAXN 30005 using namespace std; struct ArcNode { int to; struct ArcNode * next; }; struct Node { int x; friend bool operator < (Node a, Node b) { return b.x > a.x; } }; struct ArcNode * List[MAXN]; int Indegree[MAXN], Top[MAXN]; void Topological(int n) { struct ArcNode * temp; struct Node node; priority_queue <Node> Q; for(int i = 1; i<=n; i++) //将度为0的节点压入优先队列中 { if(0 == Indegree[i]) { node.x = i; Q.push(node); } } for(int i = 1; i<=n; i++) { node = Q.top(); Q.pop(); Top[i] = node.x; //按优先值大小输出 temp = List[node.x]; while(NULL != temp) { int k = temp->to; if(--Indegree[k] == 0) { node.x = k; Q.push(node); } temp = temp->next; } } } int main() { int n, m, u, v, T; struct ArcNode * temp; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); memset(List, 0, sizeof(List)); memset(Indegree, 0, sizeof(Indegree)); memset(Top, 0, sizeof(Top)); while(m--) { scanf("%d%d", &u, &v); Indegree[u]++; //反向建图 temp = (struct ArcNode *)malloc(sizeof(struct ArcNode)); temp->to = u; temp->next = NULL; if(List[v] == NULL) List[v] = temp; else { temp->next = List[v]; List[v] = temp; } } Topological(n); for(int i = n; i>1; i--) printf("%d ", Top[i]); printf("%d\n", Top[1]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/fengxmx/p/3870580.html