题意:图上的边长全是1,求从起点到每个点的最短路的条数。
题目链接:https://www.luogu.com.cn/problem/P1144
因为图是特殊的边长为1的图,所以其实是可以用bfs的,如果用spfa的话会发现任何一个点只可能进一次队列。
如果图的边长不一定,则不能直接用简单的path数组同步更新松驰,然后进队出队,会出现错误。
如果图的边长不一定,需要path数组和final数组共同记录,final表示当前走到这个点的最短路总数,path表示上面的延迟标记,表示它这里还有path条路需要进行松驰扩展,如果一个点的最短路变短了,则path和final同步更新(这种情况下能够更新它的起始点的path和final必定相同),否则如果最短路一样,则把path标记进行后推,同时更新后面这个点的path和final,更新完这个点所有出边后把path清零,表示它的延迟标记已经后推了,不需要再进行重复更新了。
代码:
#include<bits/stdc++.h>
using namespace std;
#define M 4100000
#define N 1100000
struct edge{
int n,o;
}e[M];
int last[N],flag[N],dist[N],cnt[N],final[N];
int n,m,x,y,w;
void add(int x,int y){
w++;
e[w].n=last[x];
last[x]=w;
e[w].o=y;
}
void spfa(int x){
int w1,y;
memset(dist,42,sizeof(dist));dist[x]=0;
memset(flag,0,sizeof(flag));flag[x]=1;
queue<int>q;q.push(x);
memset(cnt,0,sizeof(cnt));
cnt[x]=1;
final[x]=1;
while(q.size()){
x=q.front();q.pop();flag[x]=0;
for(w1=last[x];w1;w1=e[w1].n){
y=e[w1].o;
if(dist[x]+1<dist[y]){
dist[y]=dist[x]+1;
cnt[y]=cnt[x];
final[y]=cnt[x];
if(flag[y]==0)flag[y]=1,q.push(y);
}
else if(dist[x]+1==dist[y]){
final[y]=(final[y]+cnt[x])%100003;
cnt[y]=(cnt[y]+cnt[x])%100003;
if(flag[y]==0)flag[y]=1,q.push(y);
}
}
cnt[x]=0;
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>x>>y;
add(x,y);
add(y,x);
}
spfa(1);
for(int i=1;i<=n;i++)cout<<final[i]<<endl;
}