free (多层图最短路)

题目描述
Your are given an undirect connected graph.Every edge has a cost to pass.You should choose a path from S to T and you need to pay for all the edges in your path. However, you can choose at most k edges in the graph and change their costs to zero in the beginning. Please answer the minimal total cost you need to pay.

输入
The first line contains five integers n,m,S,T,K.
For each of the following m lines, there are three integers a,b,l, meaning there is an edge that costs l between a and b.
n is the number of nodes and m is the number of edges.

输出
An integer meaning the minimal total cost.

样例输入
3 2 1 3 1
1 2 1
2 3 2

样例输出
1

提示
1≤n,m≤103,1≤S,T,a,b≤n,0≤k≤m,1≤l≤106.
Multiple edges and self loops are allowed.

思路
建k层图跑最短路即可

代码实现

#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>

using namespace std;
typedef  long long ll;
typedef pair<int,int>P;
const int N=1005;
const int inf=0x3f3f3f3f;

struct node
{
    int p,ue,w;
    node(int _p=0,int _ue=0,int _w=0) : p(_p),ue(_ue),w(_w) {}
    bool operator < (const node &r)const
    {
        return w>r.w;
    }
};
int n,m,s,t,k;
vector<P>grp[N];
int dp[N][N];

void add(int u,int v,int w)
{
    grp[u].push_back(P(v,w));
    grp[v].push_back(P(u,w));
}

void dji()
{
    memset(dp,0x3f,sizeof(dp));
    priority_queue<node>que;
    dp[s][0]=0;
    que.push(node(s,0,0));
    while(que.size())
    {
        node top=que.top();
        que.pop();
        int u=top.p;
        if(top.ue>k) continue;
        for(int i=0;i<grp[u].size();i++)
        {
            int v=grp[u][i].first;
            int us=top.ue;
            if(dp[v][us]>dp[u][us]+grp[u][i].second)
            {
                dp[v][us]=dp[u][us]+grp[u][i].second;
                que.push(node(v,us,dp[v][us]));
            }
            if(dp[v][us+1]>dp[u][us])
            {
                dp[v][us+1]=dp[u][us];
                que.push(node(v,us+1,dp[v][us+1]));
            }
        }
    }
}
int main()
{
    scanf("%d%d%d%d%d",&n,&m,&s,&t,&k);
    for(int i=0;i<m;i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add(u,v,w);
    }
    dji();
    printf("%d\n",dp[t][k]);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值