蓝桥杯刷题记录之蓝桥王国

只是记录

这题用迪杰斯特拉来就行,我写的是堆优化版本


import java.util.*;

public class Main{
    static Scanner s = new Scanner(System.in);
    static int n,m,startPoint=1;
    static List<Edge>[] table;//邻接表,因为是稀疏图
    static long[] dist;
    static boolean[] used;
    public static void main(String[] args) {
        n = s.nextInt();
        m = s.nextInt();
        used = new boolean[n+1];
        dist = new long[n+1];
        table = new List[n+1];
        for(int i=0;i<=n;i++)
            table[i] = new ArrayList<>();
        for(int i=0;i<m;i++){
            int start = s.nextInt();
            int end = s.nextInt();
            long distance = s.nextLong();
            table[start].add(new Edge(end,distance));
        }
        dijkstra();
        for(int i=1;i<=n;i++){
            System.out.print(dist[i]==Long.MAX_VALUE?"-1 ":dist[i]+" ");
        }
        s.close();
    }
    static void dijkstra(){
        Arrays.fill(dist,Long.MAX_VALUE);
        dist[startPoint]=0;
        PriorityQueue<Edge> pq = new PriorityQueue<>((x,y)->x.distance.compareTo(y.distance));
        pq.add(new Edge(startPoint,0));
        while (!pq.isEmpty()){
            Edge poll = pq.poll();
            int t = poll.end;
            if(used[t])
                continue;
            used[t] = true;
            for(Edge item: table[t]){
                int vertex  = item.end;
                long distance = item.distance;
                if(!used[vertex] && dist[vertex] > dist[t]+distance){
                    dist[vertex] = dist[t]+distance;
                    pq.add(new Edge(vertex,dist[vertex]));
                }
            }
        }
    }
}
class Edge{
    int end;// 终点
    Long distance;//距离
    public Edge(int end,long distance){
        this.end = end;
        this.distance = distance;
    }
}

相关推荐

  1. 记录王国

    2024-03-31 00:02:01       22 阅读
  2. 记录数字王国军训排队

    2024-03-31 00:02:01       19 阅读
  3. 记录质数

    2024-03-31 00:02:01       12 阅读
  4. -每日-023

    2024-03-31 00:02:01       30 阅读
  5. -每日-024

    2024-03-31 00:02:01       30 阅读
  6. -每日-026

    2024-03-31 00:02:01       42 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-31 00:02:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-31 00:02:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-31 00:02:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-31 00:02:01       20 阅读

热门阅读

  1. C/C++ ② —— C++11智能指针

    2024-03-31 00:02:01       17 阅读
  2. 【前端学习——css篇】3.隐藏元素的方法

    2024-03-31 00:02:01       14 阅读
  3. C++蓝桥考级一级到十八级的考点内容整理

    2024-03-31 00:02:01       17 阅读
  4. js教程(10)

    2024-03-31 00:02:01       20 阅读
  5. 【阅读笔记】《你的第一本博弈论》

    2024-03-31 00:02:01       16 阅读
  6. 防范非法集资,小米消金在行动

    2024-03-31 00:02:01       17 阅读
  7. ASTM C568/C568-22 石灰石检测

    2024-03-31 00:02:01       17 阅读
  8. IDM工具v6.42.3 便携绿色

    2024-03-31 00:02:01       20 阅读
  9. 简单的聊聊Rust元组

    2024-03-31 00:02:01       21 阅读