鏈接:https://ac.nowcoder.com/acm/contest/884/J
來源:牛客網
時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 524288K,其他語言1048576K
64bit IO Format: %lld
題目描述
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
題意:在一個圖中讓k條邊的權值變爲0,然後輸出兩點之間最短距離
題解:在跑dijk最短路的同時,進行dp,dp[i][j]表示在第i個點時,讓j條邊變爲0的最短距離,這樣就能寫出遞推公式
dp[v][j]=min(dp[v][j],dp[u][j-1])
dp[v][j]=min(dp[v][j],dp[u][j]+edge[i].c)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int maxn =1e3+9;
ll dp[maxn][maxn];
int n,m,s,t,k;
int tot;
int head[maxn];
struct rt{
int v,next;
ll c;
}edge[maxn*100];
void add_edge(int u,int v,ll c){
edge[tot].v=v;
edge[tot].c=c;
edge[tot].next=head[u];
head[u]=tot++;
}
void dijk(int s){
priority_queue<P,vector<P>,greater<P> >que;
memset(dp,0x3f,sizeof(dp));
for(int i=0;i<=k;i++)dp[s][i]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top(); que.pop();
int u=p.second;
if(dp[u][0]<p.first)continue;
// cout<<u<<endl;
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].v;
int flag=0;
for(int j=1;j<=k;j++){
if(dp[v][j]>dp[u][j-1])
{
dp[v][j]=dp[u][j-1];
flag=1;
}
}
for(int j=0;j<=k;j++){
if(dp[v][j]>dp[u][j]+edge[i].c){
dp[v][j]=dp[u][j]+edge[i].c;
flag=1;
}
}
if(flag){
que.push(P(dp[v][0],v));
}
}
}
}
int main(){
memset(head,-1,sizeof(head));
scanf("%d%d%d%d%d",&n,&m,&s,&t,&k);
int u,v;
ll c;
for(int i=0;i<m;i++){
scanf("%d%d%lld",&u,&v,&c);
add_edge(u,v,c);
add_edge(v,u,c);
}
dijk(s);
printf("%lld\n",dp[t][k]);
return 0;
}