拓扑排序问题
来源:互联网 发布:javascript split 编辑:程序博客网 时间:2024/05/22 03:14
算法题:
假设有些任务需要执行,任务之间有依赖,给出一个满足条件的执行顺序。
输入:
b, a(表示b依赖于a,需要a先执行,才能执行b,其他类似)
c, b
d, a
输出:a, b, c, d
使用拓扑排序;
package com.tao;import java.util.ArrayList;import java.util.List;/** * Created by Michael on 2017/9/5. *//** * 拓扑排序 */public class Q1 { public static void main(String[] args) { String str = "bacbda"; int n = str.length()/2; //n行输入 int[][] map = new int[128][128]; //邻接矩阵 int[] outDegree = new int[128]; //出度数组 //初始化邻接矩阵和出度数组 for(int i = 0; i < str.length(); i = i + 2) { char x = str.charAt(i); char y = str.charAt(i+1); //x --> y if(map[x][y] == 0) { map[x][y] = 1; outDegree[x]++; } } //拓扑排序 List<Character> result = topoSort(map, outDegree, str); System.out.println(result); } //拓扑排序 public static List<Character> topoSort(int[][] map, int[] outDegree, String str) { List<Character> result = new ArrayList<>(); int len = outDegree.length; //n趟表示针对n行输入 for(int i = 0; i < str.length(); i++) { for(int j = 0; j < len; j++) { //找出出度为0的节点 if(outDegree[j] == 0 && inString((char)j, str)) { result.add((char) j); outDegree[j]--; //将与之关联的边去掉 for(int k = 0; k < map.length; k++) { if(map[k][j] == 1) { map[k][j] = 0; outDegree[k]--; } } break; } } } return result; } //判断字符是否在字符串中 public static boolean inString(char ch, String str) { for(int i = 0; i < str.length(); i++) { if(ch == str.charAt(i)) { return true; } } return false; }}
阅读全文
0 0
- 一个拓扑排序问题
- 拓扑排序问题
- 拓扑排序问题
- 拓扑排序问题
- 拓扑排序解成绩排名问题
- 拓扑排序问题(队列实现)
- 九度OJ 1448 拓扑排序问题
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- laya之坑--加密解密算法
- codeforces 846A Curriculum Vitae
- 04. Yii 2.0 的MVC模式
- Oracle获取所有的上级和下级 connect by
- My eclipse设置tab为4个空格
- 拓扑排序问题
- mysql集群——(二)环境搭建
- 如何设置vim里字体颜色
- GitChat · 人工智能 | 人工智能产品测试方法探索
- srm500
- udev规则以及编写
- SQL语句 函数
- Swift 中的计算属性、懒存储属性、属性观察器
- PHP DB 数据库连接类