题目描述
给出一个N个顶点M条边的无向无权图,顶点编号为1−N。问从顶点11开始,到其他每个点的最短路有几条。
输入格式
第一行包含2个正整数N,M,为图的顶点数与边数。
接下来M行,每行2个正整数x,y表示有一条顶点x连向顶点y的边,请注意可能有自环与重边。
输出格式
共N行,每行一个非负整数,第i行输出从顶点1到顶点i有多少条不同的最短路,由于答案有可能会很大,你只需要输出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。
代码
#include <cstdio>
#include <queue>
using namespace std;
#define MAXN 1000050
int read() {
int x = 0; bool f = 0; char ch = getchar();
while (!isdigit(ch)) f = (ch == 45), ch = getchar();
while ( isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? (~x + 1) : x;
}
struct edge{
int next, to;
}e[MAXN << 1];
int head[MAXN << 1], num = 0;
void addEdge(int from, int to) {
e[++num].next = head[from];
e[num].to = to;
head[from] = num;
}
int n, m;
int dis[MAXN], vis[MAXN], cnt[MAXN];//cnt[i] 记录到i点的最短路径的条数
queue<int> q;
void spfa(int s) {
for (int i = 1; i <= n; i++) {
dis[i] = 10000000;
cnt[i] = 0;
vis[i] = 0;
}
dis[s] = 0; vis[s] = 1; cnt[s] = 1; q.push(s);
do {
int u = q.front(); q.pop();vis[u] = 0;
for (int i = head[u]; i; i = e[i].next) {
int to = e[i].to;
//计数 发现的一条新的最短路径,进行更新
if (dis[to] == dis[u] + 1) {
cnt[to] = (cnt[to] + cnt[u]) % 100003;
}
//计数 发现了一条路径没有更新,进行更新
if (dis[to] > dis[u] + 1) {
dis[to] = dis[u] + 1;
cnt[to] = cnt[u]; // to 和 u 在同一条路径上,则u的cnt == to的cnt
if (!vis[to]) {
vis[to] = 1;
q.push(to);
}
}
}
}while(!q.empty());
}
int main() {
n = read(); m = read();
for (int i = 1, x, y; i <= m; i++) {
x = read(); y = read();
addEdge(x, y);addEdge(y, x);
}
spfa(1);
for (int i = 1; i <= n; i++) {
printf("%d\n", cnt[i]);
}
return 0;
}