题目:
给出一个N个顶点MMM条边的无向无权图,顶点编号为1−N。问从顶点1开始,到其他每个点的最短路有几条。
思路:
此题由于边权值可都为1,所以可以不需要SPFA或者迪杰斯拉,只需用BFS即可.
领接表有两种实现,一种是数组存储,一种则是用vector容器存储。
领接表(数组模拟)
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
AC代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 2000010;
int h[N],ne[N*2],e[N*2],idx;
int n,m;
bool st[N*2];//哪些点被搜过了
int cnt[N*2],dept[N*2];//cnt数组代表的是到这个点的方法有多少种,dept代表的是最短距离
const int mod = 100003;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;//领接表模板
}
void bfs()
{
queue<int> q;
q.push(1);
st[1]=true;
cnt[1]=1;//初始化
while(q.size())
{
int t=q.front();
q.pop();
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i]; //能从t这个点走过来的j这个点
if(!st[j]) //判断j这个点有没有走过
{
st[j]=true;
q.push(j);
dept[j]=dept[t]+1;//更新距离
}
if(dept[j]==dept[t]+1) //如果t的最短距离+1就是j的最短距离,那么更新
{
cnt[j]=(cnt[t]+cnt[j])%mod;
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
for(int i=1;i<=m;++i)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);//从a到b加一条有向边
add(b,a);//从b到a加一条有向边
}
bfs();
for(int i=1;i<=n;++i)
{
printf("%d\n",cnt[i]);
}
return 0;
}