- 最短路计数
给出一个 N 个顶点 M 条边的无向无权图,顶点编号为 1 到 N。
问从顶点 1 开始,到其他每个点的最短路有几条。
输入格式
第一行包含 2 个正整数 N,M,为图的顶点数与边数。
接下来 M 行,每行两个正整数 x,y,表示有一条顶点 x 连向顶点 y 的边,请注意可能有自环与重边。
输出格式
输出 N 行,每行一个非负整数,第 i 行输出从顶点 1 到顶点 i 有多少条不同的最短路,由于答案有可能会很大,你只需要输出对 100003 取模后的结果即可。
如果无法到达顶点 i 则输出 0。
数据范围
1≤N≤105,
1≤M≤2×105
输入样例:
5 7
1 2
1 3
2 4
3 4
2 3
4 5
4 5
输出样例:
1
1
1
2
4
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
const int mod = 100003;
int h[N], cnt = 0;
int n, m, x, y;
int ans[N], d[N], vis[N];
struct node {
int y, ne;
} s[N];
void add(int x, int y) {
s[++cnt].y = y;
s[cnt].ne = h[x];
h[x] = cnt;
}
void bfs() {
queue<int> q;
memset(d, inf, sizeof(d));
d[1] = 0;
ans[1] = 1;
q.push(1);
while (q.size()) {
int x = q.front();
q.pop();
if (vis[x]) continue;
vis[x] = 1;
for (int i = h[x]; i; i = s[i].ne) {
int y = s[i].y;
if (d[y] > d[x] + 1) {
d[y] = d[x] + 1;
ans[y] = ans[x];
q.push(y);
} else if (d[y] == d[x] + 1) {
ans[y] = (ans[y] + ans[x]) % mod;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
while (m--) {
cin >> x >> y;
add(x, y);
add(y, x);
}
bfs();
for (int i = 1; i <= n; i++) {
cout << ans[i] << '\n';
}
return 0;
}
405

被折叠的 条评论
为什么被折叠?



