拓扑排序
对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。
拓扑排序常用来确定一个依赖关系集中,事物发生的顺序。例如,在日常工作中,可能会将项目拆分成A、B、C、D四个子部分来完成,但A依赖于B和D,C依赖于D。为了计算这个项目进行的顺序,可对这个关系集进行拓扑排序,得出一个线性的序列,则排在前面的任务就是需要先完成的任务。
注意:这里得到的排序并不是唯一的!
public class Qunar2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] s= sc.nextLine().split(" ");
int n = Integer.valueOf(s[0]);//节点数
int e = Integer.valueOf(s[1]);//边数
Map<Integer, Node> graph = new HashMap<>();
Map<Integer, Integer> count = new HashMap<>();
Queue<Node> queue = new PriorityQueue<Node>();
List<Integer> output = new ArrayList<Integer>();//放输出
for (int i = 0; i < n; i++) {
int id = sc.nextInt();
int weight = sc.nextInt();
graph.put(id, new Node(id, weight));
count.put(id, 0);
}
for (int i = 0; i < e; i++) {
int start = sc.nextInt();
int end = sc.nextInt();
Node node = graph.get(start);
node.linkedNode.add(end);
int temp = count.get(end);
count.put(end, ++temp);//指向该节点的个数加1
}
for (Integer i : count.keySet()){
if (count.get(i) == 0){
queue.add(graph.get(i));
}
}
while (!queue.isEmpty()) {
Node top = queue.poll();
int id = top.id;
output.add(id);
List<Integer> list = top.linkedNode;
for (Integer i : list) {
int input = count.get(i);
count.put(i, --input);
if (input == 0)
queue.offer(graph.get(i));
}
}
for (int i = 0; i < output.size(); i++)
System.out.println(output.get(i) + " ");
}
}
class Node implements Comparable<Node> {
public int id;
public int weight;
public List<Integer> linkedNode;
public Node(int id, int weight) {
this.id = id;
this.weight = weight;
this.linkedNode = new ArrayList<Integer>();
}
@Override
public int compareTo(Node o) {
return o.weight - this.weight;
}
}
http://www.cnblogs.com/newpanderking/archive/2012/10/18/2729552.html