【最短路】CODE[VS] 1021 玛丽卡 ( Dijkstra )

本文介绍了一种使用迪杰斯特拉算法解决单源最短路径问题的方法,通过定义cost数组记录边的权值,并通过删除特定边(将其权值设为无穷大)来求解最短路径。文章还提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击躲避玛丽卡


单源最短路
定义一个cost数组记录边的权值,然后删边(改值为INF)跑最短路就行了
第一遍跑的时候,别忘了记录一下每个点的父节点,方便删边


代码如下(dijkstra):

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define maxn 2003
#define INF 1000000007

using namespace std;
typedef long long LL;

LL n,m,tot,ans = 0;
LL fa[maxn];
LL head[maxn];
LL dist[maxn];
LL cost[maxn][maxn];
bool used[maxn];

struct data
{
    LL f,t,c,next;
}es[(maxn*(maxn >> 1)) << 1];

struct node
{
    LL u,v;
    bool operator < (const node &x)const
    {
         return v > x.v;
    }
};

inline void build(LL x,LL y,LL z)
{
    tot++;
    es[tot].f = x;
    es[tot].t = y;
    es[tot].c = z;
    es[tot].next = head[x];
    head[x] = tot;
}

priority_queue<node >q;

LL dij(LL x,LL y,bool pd)
{
    memset(dist,68,sizeof(dist));
    memset(used,0,sizeof(used));
    q.push((node){x,0});
    dist[x] = 0;
    while(!q.empty())
    {
        node u = q.top();
        q.pop();
        LL now = u.u;
        if(used[now] == true) continue;
        used[now] = true;   
        for(LL i = head[now];i;i = es[i].next)
        {
            LL v = es[i].t;
            if(dist[v] > dist[now]+cost[now][v])
            {
                dist[v] = dist[now]+cost[now][v];
                if(pd) fa[v] = now;
            //  cout<<"dist of "<<v<<" : "<<dist[v]<<endl;
                q.push((node){v,dist[v]});
            }
        }
    }
//  cout<<"dist of n: "<<dist[n]<<endl;
    return dist[n];
}

inline void rd(LL &x)
{
    scanf("%lld",&x);
}

inline void work()
{
    for(LL i = 1;i <= m;i++)
    {
        LL a,b,c;
        rd(a);rd(b);rd(c);
        build(a,b,c);
        build(b,a,c);
        cost[a][b] = c;
        cost[b][a] = c;
    }
    dij(1,n,1); 
    LL s = 1,e = n;
    for(LL i = e;i != s;i = fa[i])
    {
        LL v = fa[i];
        LL x = cost[i][v];
        cost[i][v] = cost[v][i] = INF;
        ans = max(ans,dij(1,n,0));
        cost[i][v] = cost[v][i] = x;
    //  cout<<ans<<endl;
    }
    printf("%lld\n",ans);
}

int main()
{
    memset(dist,68,sizeof(dist));
    memset(used,0,sizeof(used));
    rd(n);rd(m);
    work();
return 0;
}

THE END

By Peacefuldoge

http://blog.youkuaiyun.com/loi_peacefuldog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值