牛客网 2018校招真题 去哪儿 带权的DAG节点排序

Description

牛客网 2018校招真题 带权的DAG节点排序

Solving Ideas

拓扑排序

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( n + e ) O(n+e) O(n+e)

Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

class Vertex {
    int lable; //标号
    int weight; //权值
    int in; //入度
    ArrayList<Vertex> connectList; //该顶点所指向的点
    Vertex(int lable, int weight) {
        this.lable = lable;
        this.weight = weight;
        this.connectList = new ArrayList<Vertex>();
    }
}

/**
 * 拓扑排序
 * 
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strs = br.readLine().split(" ");
        int n = Integer.parseInt(strs[0]), e = Integer.parseInt(strs[1]);

        //建图
        HashMap<Integer, Vertex> dag = new HashMap<Integer, Vertex>();
        for (int i = 0; i < n; i++) {
            strs = br.readLine().split(" ");
            int lable = Integer.parseInt(strs[0]), weight = Integer.parseInt(strs[1]);
            dag.put(lable, new Vertex(lable, weight));
        }
        for (int i = 0; i < e; i++) {
            strs = br.readLine().split(" ");
            int from = Integer.parseInt(strs[0]), to = Integer.parseInt(strs[1]);
            dag.get(from).connectList.add(dag.get(to));
            dag.get(to).in++;
        }

        ArrayList<Integer> res = topologicalSort(dag);
        for (int i = 0; i < res.size() - 1; i++) {
            System.out.print(res.get(i) + " ");
        }
        System.out.println(res.get(res.size() - 1));
    }

    private static ArrayList<Integer> topologicalSort(HashMap<Integer, Vertex> dag) {
        ArrayList<Integer> res = new ArrayList<>();

        //大顶堆
        PriorityQueue<Vertex> queue = new PriorityQueue<>(new Comparator<Vertex>() {
            @Override
            public int compare(Vertex o1, Vertex o2) {
                return -Integer.compare(o1.weight, o2.weight);
            }
        });

        //入度为0的点入队
        for (Integer lable : dag.keySet()) {
            if (dag.get(lable).in == 0) queue.offer(dag.get(lable));
        }

        while (!queue.isEmpty()) {
            Vertex fromV = queue.poll();
            res.add(fromV.lable);

            for (Vertex toV : dag.get(fromV.lable).connectList) {
                toV.in--; //邻接点入度减1
                if (toV.in == 0) queue.offer(toV);
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值