[USACO09FEB] Revamping Trails, the most experienced road in Luogu, the shortest path in layered map

The subject

      [USACO09FEB] Revamping Trails

      "Dp it"

      The meaning of the question is very simple, that is, to find the shortest path of a directed graph after removing the weights of k edges.

      We can easily think of a layered graph approach (that is, violence).

      The layered diagram just visualizes the idea of ​​​​Dp.

      d[x][p] represents the minimum cost of transforming p roads before point x.

      Then d[x][p] can be extended to two states of d[y][p]+s[i].c and d[y][p+1].

      So we can do this.

      Obviously, the number of sides is too large and cannot be done with SPFA, only with Dijkstra.

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;

int n,m,k;
int len ​​= 0;
struct edge{
	int x,p1,y,p2,next,c;
}s[1000010];
struct node{
	int x,p;
	long long d;
	bool operator<(const node y)const{
		return d>y.d;
	}
};
int first[10010];
bool tf[10010][21];
priority_queue<node> f;
long long d[10010][21];

void ins(int x,int y,int c){
	len ++;
	s[len].y=y;s[len].c=c;s[len].next=first[x];first[x]=len;
}

int main(){
	scanf("%d %d %d",&n,&m,&k);
	for(int i=1;i<=m;i++){
		int x,y,c;
		scanf("%d %d %d",&x,&y,&c);
		ins(x,y,c);ins(y,x,c);
	}
	memset(d,63,sizeof(d));
	d[1][0]=0;
	f.push((node){1,0,0});
	while(!f.empty()){
		node x=f.top();
		f.pop();
		if(tf[x.x][x.p]) continue;
		tf[x.x][x.p]=true;
		for(int i=first[x.x];i!=0;i=s[i].next){
			int y=s[i].y;
			if(d[y][x.p+1]>d[x.x][x.p] && x.p+1<=k) {
				d[y][x.p+1]=d[x.x][x.p];
				f.push((node){y,x.p+1,d[y][x.p+1]});
			}
			if(d[y][x.p]>d[x.x][x.p]+s[i].c){
				d[y][x.p]=d[x.x][x.p]+s[i].c;
				f.push((node){y,x.p,d[y][x.p]});
			}
		}
	}
	printf("%lld",d[n][k]);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325976452&siteId=291194637