【SPFA,DIJ】Day 12 提高组模拟C组 T4 路障 block

链接

https://www.luogu.org/problemnew/show/P2865

题目大意

给定一张没有负权的无向图求次短路

解题思路

垃圾水题

首先,根据熊某淇dalao所说,这道题跟一个很苟的题很像:腾讯大战360

那道题的大意是给定两个点,求出使到达这两个点距离和最小的中转点

这道题我们是用两遍 SPFA S P F A 去做的,对于次短路这题也可以用同样的解法,只需在中间枚举中转点或边且长度必须大于最短路的最长边即可

当然也可以用 DIJ D I J 毕竟数据水,毕竟没有负环,而且 DIJ D I J 还可以用堆优化和斐波那契堆优化,时间复杂度也十分可观

代码

#include<queue>
#include<cstdio>
#include<cstring>
#define N 5001
#define M 200001
#define re register
#define getchar() (S==T&&(T=(S=BB)+fread(BB,1,1<<15,stdin),S==T)?EOF:*S++)
using namespace std;int f,n,m,x,y,w,ans=2147483647,l[N],tot,dis_s[N],dis_t[N],SP;
struct node{int next,to,w;}e[M];
char c;
queue<int>q;
bool vis[N];
inline void add(re int u,re int v,re int w)
{
    e[++tot]=(node){l[u],v,w};l[u]=tot;
    e[++tot]=(node){l[v],u,w};l[v]=tot;
    return;
}
char BB[1<<15],*S=BB,*T=BB;
inline int read() 
{
    f=0;
    while(c=getchar(),c<=47||c>=59);f=(f<<3)+(f<<1)+c-48;
    while(c=getchar(),c>=48&&c<=57) f=(f<<3)+(f<<1)+c-48;
    return f;
}
inline void spfa(re int S,re int *dis)//spfa
{
    while(q.size()) q.pop();
    q.push(S);vis[S]=true;dis[S]=0;
    while(q.size())
    {
        int x=q.front();q.pop();vis[x]=true;
        for(re int i=l[x];i;i=e[i].next)
        {
            int y=e[i].to,w=e[i].w;
            if(dis[x]+w<dis[y])
            {
                dis[y]=dis[x]+w;
                if(!vis[y]) vis[y]=true,q.push(y);
            }
        }
        vis[x]=false;
    }
    return;
}
signed main()
{
    freopen("block.in","r",stdin);
    freopen("block.out","w",stdout);
    n=read();m=read();
    for(re int i=0;i<m;i++) x=read(),y=read(),w=read(),add(x,y,w);
    memset(dis_s,0x3f3f3f3f,sizeof(dis_s));
    memset(dis_t,0x3f3f3f3f,sizeof(dis_t));
    spfa(1,dis_s);
    memset(vis,0,sizeof(0));//记得清0
    spfa(n,dis_t);//spfa求最短路
    SP=dis_s[n];//Shortest Path,原先最短路
    for(re int i=1;i<=n;i++)
     for(re int j=l[i];j;j=e[j].next)
     {
        y=e[j].to;w=e[j].w;
        if(dis_s[i]+dis_t[y]+w>SP&&dis_s[i]+dis_t[y]+w<ans)//必须是次短路才保存
         ans=dis_s[i]+dis_t[y]+w;
     }
     printf("%d",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值