HDU1285(拓扑排序(模板))
2012-07-31 15:48
260 查看
拓扑排序:
思想:1、在有向图中选择一个没有前驱的顶点并且输出
2、从图中删除该节点和所有以它为尾的弧。
重复上述步骤,知道全部顶点都已经输出,或者当前图中不存在无前驱的顶点为止。后面一种情况说明有向图中存在环。
HDU1285:http://acm.hdu.edu.cn/showproblem.php?pid=1285
思想:1、在有向图中选择一个没有前驱的顶点并且输出
2、从图中删除该节点和所有以它为尾的弧。
重复上述步骤,知道全部顶点都已经输出,或者当前图中不存在无前驱的顶点为止。后面一种情况说明有向图中存在环。
HDU1285:http://acm.hdu.edu.cn/showproblem.php?pid=1285
package D0731; import java.util.*; //图谱排序(邻接矩阵实现图存储) public class HDU1285_2 { static int n, m; static int[] indegree;// 顶点的入度 static int[] result;// 保存最后排好序的结果 static int[][] G;// 邻接矩阵存储 static Queue<Integer> que; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { n = sc.nextInt(); m = sc.nextInt(); G = new int[n + 1][n + 1]; indegree = new int[n + 1]; while (m-- > 0) { int u = sc.nextInt(); int v = sc.nextInt(); if (G[u][v] == 0) {// 这个条件一定要,否则WA,避免重边的情况比如a b可能出现两次的情况 indegree[v]++; G[u][v] = 1; } } topsort(); // 输出 System.out.print(result[1]); for (int i = 2; i <= n; i++) { System.out.print(" "+result[i]); } System.out.println(); } } private static void topsort() { result = new int[n + 1]; que = new PriorityQueue<Integer>(); int index = 0; for (int i = 1; i <= n; i++) { if (indegree[i] == 0) que.add(i); } while (!que.isEmpty()) { int u = que.poll(); result[++index] = u; for (int i = 1; i <= n; i++) { if (G[u][i] == 1) { indegree[i]--; if (indegree[i] == 0) que.add(i); } } } } }
package D0731; import java.util.*; //拓扑排序(使用邻接表实现) public class HDU1285_3 { static int n, m; static int[] indegree;// 顶点的入度 static int[] result;// 保存最后排好序的结果 static List<ArrayList<Integer>> G;// 邻接表。 static Queue<Integer> que; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { n = sc.nextInt(); m = sc.nextInt(); G = new ArrayList<ArrayList<Integer>>(); for(int i = 1;i<=n+1;i++) G.add(new ArrayList<Integer>()); indegree = new int[n + 1]; while (m-- > 0) { int u = sc.nextInt(); int v = sc.nextInt(); if (!G.get(u).contains(v)) {// 这个条件一定要,否则WA,避免重边的情况比如a b可能出现两次的情况 indegree[v]++; G.get(u).add(v); } } topsort(); // 输出 System.out.print(result[1]); for (int i = 2; i <= n; i++) { System.out.print(" " + result[i]); } System.out.println(); } } private static void topsort() { result = new int[n + 1]; que = new PriorityQueue<Integer>(); int index = 0; for (int i = 1; i <= n; i++) { if (indegree[i] == 0) que.add(i); } while (!que.isEmpty()) { int v = que.poll(); result[++index] = v; for (int i : G.get(v)) { indegree[i]--; if (indegree[i] == 0) que.add(i); } } } }
相关文章推荐
- HDU1285 确定比赛名次(拓扑排序模板)
- [hdu1285]拓扑排序模板 邻接表加优先队列简单易懂
- 拓扑排序-HDU1285-HDU2647-HDU2094-HDU1811
- 可做模板_拓扑排序
- 拓扑排序(邻接阵)模板
- hdu1285 确定比赛名次 (简单拓扑排序)
- hdu 1285 确定比赛名次 简单的拓扑排序模板题~~需要注意重边
- UVa 10305 Ordering Tasks (拓扑排序模板)
- hdu1285(拓扑排序)
- 【hdu1285】【拓扑排序】 确定比赛名次
- 确定比赛名次---HDU1285(拓扑排序)
- HDU1285:确定比赛名次(拓扑排序)
- 拓扑排序模板
- HDU1285 确定比赛名次(拓扑排序)
- 拓扑排序 模板
- 转:【拓扑排序详解】+【模板】
- hdu1285(拓扑排序)
- 拓扑排序模板
- HDU1285-拓扑排序
- HDU 1285 确定比赛名次(拓扑排序模板)