链接:https://ac.nowcoder.com/acm/contest/884/J
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≤n,m≤103,1≤S,T,a,b≤n,0≤k≤m,1≤l≤1061≤n,m≤103,1≤S,T,a,b≤n,0≤k≤m,1≤l≤106.
Multiple edges and self loops are allowed.
1 #include <iostream> 2 #include <queue> 3 #include <cstring> 4 using namespace std; 5 6 const int N = int(1e3) + 10; 7 const int INF = 0x3f3f3f3f; 8 9 struct Edge{ 10 int to,w,next; 11 }e[N+N]; 12 13 int cnt,head[N],K; 14 15 void add(int a,int b,int w){ 16 int id = ++cnt; 17 e[id].to=b; 18 e[id].w=w; 19 e[id].next=head[a]; 20 head[a]=id; 21 } 22 23 struct Node{ 24 int num,dis,k; 25 bool operator < (const Node& x)const{ 26 return dis > x.dis; 27 } 28 }; 29 30 int vis[N][N],dis[N][N]; 31 32 void Dijkstra(int s){ 33 priority_queue<Node> q; 34 memset(vis, 0, sizeof(vis)); 35 memset(dis, INF, sizeof(dis)); 36 dis[s][0]=0; 37 q.push(Node{s,dis[s][0],0}); 38 while(!q.empty()){ 39 Node x =q.top(); 40 q.pop(); 41 int n=x.num; 42 int k=x.k; 43 if(vis[n][k]) continue; 44 vis[n][k]=1; 45 for(int i =head[n]; i != -1; i=e[i].next){ 46 int v=e[i].to,w=e[i].w; 47 if(k < K && dis[n][k] < dis[v][k+1]){ 48 dis[v][k+1]=dis[n][k]; 49 q.push(Node{v,dis[v][k+1],k+1}); 50 } 51 if(dis[n][k] + w < dis[v][k]){ 52 dis[v][k] = dis[n][k] + w; 53 q.push(Node{v,dis[v][k],k}); 54 } 55 } 56 } 57 } 58 59 int main(){ 60 ios::sync_with_stdio(0); 61 memset(head,-1,sizeof(head)); 62 int n,m,S,T; 63 cin>>n>>m>>S>>T>>K; 64 while(m--){ 65 int a,b,l; 66 cin>>a>>b>>l; 67 add(a,b,l); 68 add(b,a,l); 69 } 70 Dijkstra(S); 71 int ans=INF; 72 for(int i=0;i<=K;i++) ans=min(ans,dis[T][i]); 73 cout<<ans<<endl; 74 }