dijkstra模板

该代码实现了一个使用Dijkstra算法寻找图中节点间最短路径的Java程序。通过构建优先队列来处理节点,动态更新最短距离,并使用邻接表存储图的结构。程序首先读入图的边和权重,然后应用Dijkstra算法计算从源点到所有其他点的最短距离。
摘要由CSDN通过智能技术生成
	static void dijkstra() {
		PriorityQueue<PII> q = new PriorityQueue<PII>((a,b) -> (a.x - b.x));
		q.add(new PII(0,0));
		Arrays.fill(dist,INF);
		dist[0] = 0;
		while(q.size()>0) {
			PII t = q.poll();
			int ver = t.y;
			if(st[ver]) continue;
			st[ver] = true;
			for(int i = h[ver]; i != -1; i = ne[i]) {
				int j = e[i];
				if(dist[j] > dist[ver] + w[i]) {
					dist[j] = dist[ver] + w[i];
					q.add(new PII(dist[j],j));
				}
			}
		}
	}

例题

1488. 最短距离


import java.util.*;
public class Main {
	static int INF = 0x3f3f3f;
	static int N = 100005;
	static int M = N*3;
	static long mod = 1000000007;
	//static long[] a = new long[N];
//	static int[] vis = new int[N];
//	static int[] num = new int[N];
//	static int[] diff = new int[N];
	static long n;
	//static ArrayList<Integer> []lists;
	//static long dp[][] = new long [5005][5005];
	//static int a[] = new int [N];
	static int h[] = new int [N];
	static int e[] = new int [M];
	static int w[] = new int [M];
	static int ne[] = new int [M];
	static int dist[] = new int[N];
	static boolean st[] = new boolean [N];
	static int idx = 0;
	static void add(int a,int b,int c) {
		e[idx] = b;
		w[idx] = c;
		ne[idx] = h[a];
		h[a] = idx ++;
	}
	
	static void dijkstra() {
		PriorityQueue<PII> q = new PriorityQueue<PII>((a,b) -> (a.x - b.x));
		q.add(new PII(0,0));
		Arrays.fill(dist,INF);
		dist[0] = 0;
		while(q.size()>0) {
			PII t = q.poll();
			int ver = t.y;
			if(st[ver]) continue;
			st[ver] = true;
			for(int i = h[ver]; i != -1; i = ne[i]) {
				int j = e[i];
				if(dist[j] > dist[ver] + w[i]) {
					dist[j] = dist[ver] + w[i];
					q.add(new PII(dist[j],j));
				}
			}
		}
	}
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        for(int i=0;i<N;i++) {
        	h[i] = -1;
        }
        while(m-->0) {
        	int a,b,c;
        	a = sc.nextInt();
        	b = sc.nextInt();
        	c = sc.nextInt();
        	add(a, b, c);
        	add(b, a, c);
        }
        int k = sc.nextInt();
        while(k-->0) {
        	int x = sc.nextInt();
        	add(0, x, 0);
        }
        dijkstra();
        int q = sc.nextInt();
        while(q-->0) {
        	int x = sc.nextInt();
        	System.out.println(dist[x]);
        }
        sc.close();
    }
}
class PII{
	int x;
	int y;
	public PII(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	public PII() {
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值