P1144 最短路计数
题目描述
给出一个N个顶点M条边的无向无权图,顶点编号为1−N。问从顶点1开始,到其他每个点的最短路有几条。
输入格式
第一行包含2个正整数N,M,为图的顶点数与边数。
接下来M行,每行2个正整数x,y,表示有一条顶点x连向顶点y的边,请注意可能有自环与重边。
输出格式
共N行,每行一个非负整数,第i行输出从顶点1到顶点i有多少条不同的最短路,由于答案有可能会很大,你只需要输出ansmod100003 后的结果即可。如果无法到达顶点i则输出0。
输入 #1
5 7
1 2
1 3
2 4
3 4
2 3
4 5
4 5
输出 #1
1
1
1
2
4
题目分析:
- 用邻接表将图存储,从顶点1开始用队列对图进行广搜,并用vis标记已被搜到的边,用foot[j]记录到达过j点的最短路径长度,用s[i]记录到达 i 点最短路径的条数
- 假如s[i]=2;将i点相联通的点压入队列,加入存在i到j的路,且为最短路径,则s[j]+=s[i];因为顶点1到i的最短路径有两条,i到j路径数量输为m,则从1到j的最短数量为m*s[i];
邻接表的建立:
(下面的方法着实麻烦了点,完全可以用vector实现)
void add(int a,int b)
{
cnt++;
p[cnt].last=h[a];//记录上家
h[a]=cnt;//更新上家
p[cnt].v=b;
}
struct node
{
int last;//上家
int v;//终点
}p[4000005];
struct node1
{
int step;
int ans;
};
int m,n;
int main()
{
int x,y;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
代码实现:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
int n,m;//n个顶点m条边
struct node
{
int last;//上家
int v;//终点
}p[4000005];
struct node1
{
int step;
int ans;
};
typedef struct node node;
int h[4000005];//记录上家
int foot[4000005];
int s[4000005]={0};//记录
int vis[4000005]={0};
int cnt=0;
void add(int a,int b)
{
cnt++;
p[cnt].last=h[a];//记录上家
h[a]=cnt;//更新上家
p[cnt].v=b;
}
void bfs()//第,走的步数
{
int i,j;
node1 a,b;
queue <node1>q;
a.step=0;
a.ans=1;
q.push(a);
s[1]=1;
foot[1]=1;
while(!q.empty())
{
a=q.front();
q.pop();//出队
for(i=h[a.ans];i&&(vis[i]==0);i=p[i].last)
{
vis[i]=1;//标记
b.step=a.step+1;//步数加一
b.ans=p[i].v;//将终点放入结构体
if(foot[p[i].v]==0)
{
foot[p[i].v]=b.step;
s[p[i].v]=(s[a.ans]+s[p[i].v])%100003;
}
else if(foot[p[i].v]==b.step)
{
s[p[i].v]=(s[a.ans]+s[p[i].v])%100003;
}
q.push(b);
}
}
}
int main()
{
int x,y;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
bfs();
for(int i=1;i<=n;i++)
printf("%d\n",s[i]%100003);
return 0;
}