1134. 最短路计数

  1. 最短路计数

给出一个 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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值