洛谷 P1144 最短路计数(java实现)

P1144 最短路计数

题目描述

给出一个N个顶点M条边的无向无权图,顶点编号为1-N。问从顶点1开始,到其他每个点的最短路有几条。

输入格式

第一行包含2个正整数N,M为图的顶点数与边数。

接下来M行,每行22个正整数x,y,表示有一条顶点x连向顶点y的边,请注意可能有自环与重边。

输出格式

共NN行,每行一个非负整数,第 i 行输出从顶点1到顶点ii有多少条不同的最短路,由于答案有可能会很大,你只需要输出ans mod100003后的结果即可。如果无法到达顶点 i 则输出0。

输入输出样例

输入 #1

5 7
1 2
1 3
2 4
3 4
2 3
4 5
4 5

输出 #1

1
1
1
2
4

说明/提示

1到5的最短路有4条,分别为2条1-2-4-5和2条1-3-4-5(由于4-5的边有2条)。

对于20%的数据,N ≤ 100;

对于60%的数据,N ≤ 1000;

对于100%的数据,N<=1000000,M<=2000000。

题解

package p1144;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.PriorityQueue;

public class Main {
	static int N = 1000010,M = 2000010,INF = 0x3f3f3f3f,MOD = 100003;
	static int n,m;
	static int h[]= new int[N],e[] = new int[M],ne[] = new int[M],idx=0;
	static int dist[] = new int[N];
	static int count[] = new int[N];
	static boolean st[] = new boolean[N];
	public static void add(int a,int b) {
		e[idx] = b;ne[idx] = h[a];h[a] = idx++;
	}
	public static void dijkstra() {
		PriorityQueue<Pair> q = new PriorityQueue<>();
		Arrays.fill(dist, INF);
		Arrays.fill(st, false);
		q.add(new Pair(1,0));
		dist[1] = 0;
		count[1] = 1;
		while(!q.isEmpty()) {
			Pair p = q.poll();
			int t = p.x;
			int dis = p.y;
			if(st[t]) continue;
			st[t] = true;
			for(int i =h[t];i!=-1;i= ne[i]) {
				int j = e[i];
				if(dist[j] == dis + 1) {
					count[j] += count[t];
					count[j] %= MOD;
				}
				if(dist[j] > dis + 1) {
					count[j] = count[t];
					dist[j] = dis + 1;
					q.add(new Pair(j,dist[j]));
				}
			}
		}
	}
	public static void main(String[] args) throws Exception{
		Read r = new Read();
		n = r.nextInt();m = r.nextInt();
		Arrays.fill(h, -1);
		while(m-->0) {
			int a = r.nextInt(),b = r.nextInt();
			add(a,b);add(b,a);
		}
		dijkstra();
		for(int i=1;i<=n;i++) {
			System.out.println(count[i]);
		}
	}
}
class Pair implements Comparable<Pair>{
	int x,y;
	public Pair(int x,int y) {
		this.x = x;
		this.y = y;
	}
	@Override
	public int compareTo(Pair o) {
		return this.y - o.y;
	}

}
class Read{
	StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
	public int nextInt() throws Exception{
		st.nextToken();
		return (int)st.nval;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜柠函

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值