首页 > 试题广场 >

Sum of Minimum Distatnce

[编程题]Sum of Minimum Distatnce
  • 热度指数:15 时间限制:C/C++ 5秒,其他语言10秒 空间限制:C/C++ 2048M,其他语言4096M
  • 算法知识视频讲解
Give a undirected graph, each edge’s length is 1, each node has a numeric ID. There are some special nodes in the graph, node’s the minimum distance to the special node is the length of shortest path to the nearest special node. Please calculate all the nodes’ minimum distance to special node. If a node could not reach any special node the distance is –1.

输入描述:
First line is a number N means that the next N lines are the N edges in the graph. Each of the N lines has two value v1 v2 which are the two nodes’ ID linked by this edge. 0 < N < 10000000
After that there is a single line with a number M which means the next M lines are the M special nodes. Each of the M lines has one value v which means the node’s ID. 0 <= M <= N/2


输出描述:
Sum of All nodes' minimum distance
示例1

输入

2
1 2
2 3
1
2

输出

2
import java.util.*;
public class Main {
    // 迪杰斯特拉算法-取特殊点不断更新最后求和
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        // 构建无向图的邻接表-坑点在于不知道结点的范围我们默认取[0,10000000)
        LinkedList<int[]>[] graph = new LinkedList[10000000];
        for (int i = 0; i < 10000000; i++) {
            graph[i] = new LinkedList<>();
        }
        // 记录一下结点的范围用于计算
        int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            int start = in.nextInt(), end = in.nextInt();
            max = Math.max(Math.max(max, end), start);
            min = Math.min(Math.min(min, end), start);
            graph[start].add(new int[]{end, 1});
            graph[end].add(new int[]{start, 1});
        }
        dis = new int[10000000];
        Arrays.fill(dis, Integer.MAX_VALUE);
        // 调用
        int m = in.nextInt();
        for (int i = 0; i < m; i++) {
            int special = in.nextInt();
            dijkstra(graph, special);
        }
        int sum = 0;
        for (int i = min; i <= max; i++) { // 注意从min开始到max计算即可
            if (dis[i] == Integer.MAX_VALUE) sum += -1;
            else sum += dis[i];
        }
        System.out.println(sum);
    }
    
    static int[] dis;
    // 迪杰斯特拉eng算就是了
    public static void dijkstra(LinkedList<int[]>[] graph, int start) {
        dis[start] = 0;
        PriorityQueue<int[]> q = new PriorityQueue<>((a, b)->a[1]-b[1]);
        q.offer(new int[]{start, 0});
        while (!q.isEmpty()) {
            int[] node = q.poll();
            int id = node[0], d = node[1];
            if (dis[id] < d) continue;
            for (int[] next : graph[id]) {
                int nid = next[0], nd = next[1];
                if (dis[id] + nd < dis[nid]) {
                    dis[nid] = dis[id] + nd;
                    q.offer(new int[]{nid, dis[nid]});
                }
            }
        }
    }
}
发表于 2022-07-20 14:41:23 回复(0)
为什么没答案,也没评论的呀
发表于 2019-11-18 21:41:30 回复(0)