题目链接:P1144 最短路计数
程序说明:
如果搜索到的点到起点的距离等于当前点到起点的距离加上这两点间的那条边的距离,那么我们就将搜索到的点的路径数加上当前点的路径数。
如果我们更新了搜索到的点到起点的最短距离,那么我们将到达改点的路径数改为当前点的路径数。(参考P1608 路径统计 题解)
因此将spfa的松弛操作修改为:
//cnt[]记录路径数
if(dist[j] > dist[t] + 1) {
dist[j] = dist[t] + 1;
cnt[j] = cnt[t];
}
else if(dist[j] == dist[t] + 1)
cnt[j] += cnt[t];
代码如下:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e6 + 10, M = 2 * N;
int h[N], e[N], ne[N], idx;
int n, m, dist[N], st[N], cnt[N];
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void spfa() {
memset(dist, 0x3f, sizeof dist);
queue<int> q;
q.push(1);
st[1] = 1;
dist[1] = 0;
cnt[1] = 1;
while(!q.empty()) {
int t = q.front();
q.pop();
st[t] = 0;
for(int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[t] + 1) {
dist[j] = dist[t] + 1;
cnt[j] = cnt[t];
cnt[j] %= 100003;
if(!st[j]) {
st[j] = 1;
q.push(j);
}
}
else if(dist[j] == dist[t] + 1) {
cnt[j] += cnt[t];
cnt[j] %= 100003;
}
}
}
}
int main() {
memset(h, -1, sizeof h);
cin>>n>>m;
while(m--) {
int x, y;
cin>>x>>y;
add(x, y), add(y, x); //无向图
}
spfa();
for(int i = 1; i <= n; i++)
cout<<cnt[i]<<endl;
return 0;
}