题目描述
传送门
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.
示例1
输入
3 2 1 3 1
1 2 1
2 3 2
输出
1
备注:
1≤n,m≤10e3,1≤S,T,a,b≤n,0≤k≤m,1≤l≤10e6.
Multiple edges and self loops are allowed.
思路:
二维最短路,dp[i][j]代表从起点到i点,最多免费走j条边的最小费用
dp[i][j]=min(dp[i][j-1],min(dp[x][j-1],dp[x][j]+e));(x和i有边权为e的边)
以min(dp[i][j-1],dp[x][j-1])作为i号点的初始距离,使用dijkstra跑最短路
参考代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
const int MAX_N=1e3+5;
struct edge{
int to,cost;
};
int n,m,s,t,k;
vector<edge> G[MAX_N];
int d[MAX_N][MAX_N+1];
void dijkstra(int f){
priority_queue<P,vector<P>,greater<P> >que;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();que.pop();
int v=p.second;
if(d[v][f]<p.first)continue;
for(int i=0;i<G[v].size();i++){
edge &e=G[v][i];
if(d[e.to][f]>d[v][f]+e.cost){
d[e.to][f]=d[v][f]+e.cost;
que.push(P(d[e.to][f],e.to));
}
}
}
}
int main(){
scanf("%d%d%d%d%d",&n,&m,&s,&t,&k);s--,t--;
for(int i=0;i<m;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);u--,v--;
G[u].push_back((edge){v,w});
G[v].push_back((edge){u,w});
}
for(int i=0;i<n;i++)d[i][0]=INF;
d[s][0]=0;
dijkstra(0);
for(int i=1;i<=k;i++){
for(int v=0;v<n;v++)d[v][i]=d[v][i-1];
for(int v=0;v<n;v++){
for(int j=0;j<G[v].size();j++){
edge &e=G[v][j];
d[e.to][i]=min(d[e.to][i],d[v][i-1]);
}
}
dijkstra(i);
}
printf("%d\n",d[t][k]);
return 0;
}