D - Number of Shortest paths

先跑一次最短路,然后通过动态规划找出最短路的个数

#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>

using namespace std;
typedef long long ll;
const int N = 2e5 + 10, M = 8e5 + 10;
const ll mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
int h[N], ne[M], e[M], idx;
int n, m;
bool st[N];
int dis[N];
typedef pair<int, int> PII;
int c[N];
void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void bfs()
{
    queue<int> t;
    t.push(1);
    dis[1] = 0;
    c[1] = 1;
    st[1] = 1;
    while (t.size()) {
        int w = t.front();
        t.pop();
        st[w] = 0;
        for (int i = h[w]; i != -1; i = ne[i]) {
            int j = e[i];
            if (dis[j] > dis[w] + 1) {
                dis[j] = dis[w] + 1;
                c[j] = (c[w] + c[j]) % mod;
                if (!st[j]) {
                    st[j] = 1;
                    t.push(j);
                }
            } else if (dis[j] == dis[w] + 1)
                c[j] = (c[w] + c[j]) % mod;
        }
    }
}

int main()
{
    cin.tie(0)->sync_with_stdio(0);
    cin >> n >> m;
    memset(h, -1, sizeof h);
    memset(dis, 0x3f, sizeof dis);
    while (m--) {
        int a, b;
        cin >> a >> b;
        add(a, b);
        add(b, a);
    }
    bfs();
    if (dis[n] == inf)
        cout << 0;
    else
        cout << c[n];
    return 0;
}
posted @   Flying_bullet  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示