【笔试题】去哪儿笔试--有向无环图

这里写图片描述
这里写图片描述

拓扑排序

对一个有向无环图(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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值