洛谷P2939 [USACO09FEB]Revamping Trails G

topic

topic

John, a total of N) ranch. Covered by the dust of the M trail connection. Trails can be two-way traffic. Every morning John from ranch to ranch 1 to N cows physical examination.
Through each trail needs to consume a certain amount of time. John K which intend to upgrade the trail, making it a highway. traffic on the highway is almost instantaneous, so the passage of time the highway is 0.
Please help John to decide which trails to upgrade, make him every day from 1 No. No. N ranch to ranch spent the shortest time

Code

Standard hierarchical view of
pay attention to use the stack optimized Dijkstra, with SPFA will fly T

#include <iostream>
#include <utility>
#include <cstring>
#include <queue>
#define mp(x,y) make_pair(x,y)

using namespace std;
const int N=1E5*70,M=5E7;
int to[M],val[M],nxt[M],head[N],cnt;
int dist[N];
bool vis[N];
int n,m,k;

void add(int u,int v,int w) {
	to[++cnt]=v;
	val[cnt]=w;
	nxt[cnt]=head[u];
	head[u]=cnt;
}

void dijkstra() {   //这题卡SPFA,只能用堆优化的Dijkstra
	memset(dist,0x3f,sizeof(dist));
	dist[1]=0;
	priority_queue<pair<int,int> > q;
	q.push(mp(0,1));
	while(!q.empty()) {
		int x=q.top().second;
		q.pop();
		vis[x]=true;
		for(int i=head[x];i;i=nxt[i]) {
			int y=to[i],w=val[i];
			if(dist[y]>dist[x]+w) {
				dist[y]=dist[x]+w;
				if(!vis[y])
				  q.push(mp(-dist[y],y));
			}
		}
	}
}

int main() {
	cin>>n>>m>>k;
	while(m--) {
		int u,v,w;
		cin>>u>>v>>w;
		add(u,v,w);
		add(v,u,w);
		for(int j=1;j<=k;j++) {
			add(v+j*n,u+j*n,w);
			add(u+j*n,v+j*n,w);
			add(v+j*n-n,u+j*n,0);
			add(u+j*n-n,v+j*n,0);
		}
	}
	dijkstra();
	int ans=0x7fffffff; //防极品数据
	for(int i=1;i<=k;i++)
	  ans=min(ans,dist[i*n+n]);
	cout<<ans;
	return 0;
}

Guess you like

Origin www.cnblogs.com/wyc06/p/12641813.html