[图论 最短路 spfa]分糖果

今天给大家讲解分糖果这道题目

在这里插入图片描述

思路

很简单,我们把小朋友看作点,两个小朋友在彼此身旁看作是一条无向图的路径,路径的权值为 1 1 1。现在糖果 c c c小朋友身上,让我们求出传给其他小朋友之后,吃完糖的最小时间。

求最小时间,也就是求出距离 c c c点最远的点的最小距离。

很简单,这就是一个单源点最短路。我们可以运用 s p f a spfa spfa算法来解决。

代码

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int cnt;
int fst[5000005];
int n,p,c;
int m;
struct edge
{
    int nxt,to,w;
}arr[5000005];
void adds(int x,int y)//建边
{
    arr[++cnt].to=y,arr[cnt].nxt=fst[x],fst[x]=cnt;
}
queue<int> q;
int vis[1000005];
int dis[1000005];
int ans;
//直接套spfa模版
void spfa()
{
    memset(dis,0x3f,sizeof(dis));
    q.push(c);
    vis[c]=1;
    dis[c]=0;
    while(!q.empty())
    {
        int x=q.front();
        vis[x]=0;
        q.pop();
        for(int i=fst[x];i;i=arr[i].nxt)
        {
            int tmp=arr[i].to;
            if(dis[tmp]>dis[x]+1)
            {
                dis[tmp]=dis[x]+1;
                if(vis[tmp]==0)
                {
                    vis[tmp]=1;
                    q.push(tmp);
                }
            }
        }
    }
}
int main()
{
    //输入
    scanf("%d%d%d",&n,&p,&c);
    scanf("%d",&m);
    for(int i=1;i<=p;++i)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        adds(x,y);//调用建边函数
        adds(y,x);
    }
    spfa();//调用spfa函数
    for(int i=1;i<=n;++i)
    {
        ans=max(ans,dis[i]);//求出距离c权值最大的边
    }
    ans+=m;//加上吃糖果的时间
    cout<<ans+1<<endl;//记得+1
}

完结撒花

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值