本题思路:运用bfs宽搜思想(其实也算spfa啦)
因为每条边的权值都为1,所以每个点第一次被搜到的点一定是最短路
接下来看核心代码吧!
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10,M=3e6+10;
int h[N],e[M],ne[M],idx;
int d[N],cnt[N];
int n,m;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs()
{
memset(d,0x3f,sizeof(d));
queue<int> q;
q.push(1);
d[1]=0;
cnt[1]=1;
while(q.size())
{
auto t= q.front();
q.pop();
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(d[j]>d[t]+1)//如果进入这个if,说明j点为第一次被搜到,并且d[t]+1为j的最短路
{
d[j]=d[t]+1;//修改最短路的值
q.push(j);//加入队列
}
//如果t到j的距离等于j的最短路j,那么就把t的最短路条数加到cnt[j]上,这个可以自己模拟得出
//后面的最短路条数,等于所有到达j为最短路的点的cnt[]边数之和
if(d[j]==d[t]+1) cnt[j]=(cnt[j]+cnt[t])%100003; //记得对答案取模
}
}
for(int i=1;i<=n;i++) cout<<cnt[i]%100003<<endl;//我比较求稳,输出也取一遍模,其实没必要,但没关系不影响答案
}
int main()
{
//快读快写
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(h,-1,sizeof(h));
cin>>n>>m;
int a,b;
while(m--)
{
cin>>a>>b;
add(a,b);
add(b,a);
}
bfs();
return 0;
}