最短路计数(入门最短路)

题目:

给出一个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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值