【题解】P1144 最短路计数

题目传送门

没有边权的无向图,模数 p=100003p=100003。

首先去掉自环,bfs 一遍可以求出每个点的最短路 depidep_i。

然后再 bfs 一遍,如果节点 ii 与节点 jj 连边,且 depi+1=depjdep_i+1=dep_j,那么就说明 jj 能够被 ii 更新,也就是说边 (i,j)(i,j) 是在点 jj 的其中一条最短路上,于是有 ansj=(ansj+ansi) mod pans_j=(ans_j+ans_i) \bmod p。

这样两遍 bfs 即可。

时间复杂度 O(n+m)O(n+m)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<bits/stdc++.h>
#define ll long long
#define back return
#define ri register int
#define ull unsigned ll
using namespace std;
ll read()
{
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
back x*f;
}
const int mod=100003;
int n,m,dep[1000005],ans[1000005],vis[1000005];
vector<int> a[1000005];
queue<int> q;
void bfs()
{

}
int main()
{
n=read(),m=read();
for(ri i=1;i<=m;i++)
{
int x=read(),y=read();
if(x==y)
continue;
a[x].push_back(y);
a[y].push_back(x);
}
q.push(1),vis[1]=1,ans[1]=1,dep[1]=0;
while(!q.empty())
{
int now=q.front();
q.pop();
for(ri i=0;i<a[now].size();i++)
{
int to=a[now][i];
if(vis[to])
continue;
vis[to]=1;
q.push(to);
dep[to]=dep[now]+1;
}
}
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
q.push(1);
while(!q.empty())
{
int now=q.front();
q.pop();
if(vis[now])
continue;
vis[now]=1;
for(ri i=0;i<a[now].size();i++)
{
int to=a[now][i];
if(dep[to]==dep[now]+1)
ans[to]=(ans[to]+ans[now])%mod;
q.push(to);
}
}
for(ri i=1;i<=n;i++)
cout<<ans[i]<<"\n";
back 0;
}