【題解】LuoGu4568:[JLOI2011]飛行路線

原題傳送門
很妙的套路,分層圖
跟以前的一道題目比較比較

建立(k+1)(k+1)層圖,相鄰兩層的點之間可以互相走到就是走一條免費邊
起點是ss,終點是kn+tk*n+t

Code:

#include <bits/stdc++.h>
#define maxn 2500010
using namespace std;
struct Edge{
	int to, next, len;
}edge[maxn << 1];
struct node{
	int val, len;
	bool operator < (const node &x) const{ return x.len < len; }
};
priority_queue <node> q;
int num, head[maxn], n, m, k, S, T, dis[maxn], vis[maxn];

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

void addedge(int x, int y, int z){ edge[++num] = (Edge){y, head[x], z}, head[x] = num; }

int main(){
	n = read(), m = read(), k = read();
	S = read(), T = read();
	for (int i = 1; i <= m; ++i){
		int x = read(), y = read(), z = read();
		for (int j = 0; j <= k; ++j){
			addedge(j * n + x, j * n + y, z), addedge(j * n + y, j * n + x, z);
			if (j <= k) addedge(j * n + x, (j + 1) * n + y, 0), addedge(j * n + y, (j + 1) * n + x, 0);
		}
	}
	for (int i = 0; i <= k; ++i) addedge(i * n + T, (i + 1) * n + T, 0);
	memset(dis, 0x3f, sizeof(dis));
	dis[S] = 0;
	q.push((node){S, 0});
	while (!q.empty()){
		node tmp = q.top(); q.pop();
		int u = tmp.val;
		if (vis[u]) continue;
		vis[u] = 1;
		for (int i = head[u]; i; i = edge[i].next){
			int v = edge[i].to;
			if (dis[v] > dis[u] + edge[i].len){
				dis[v] = dis[u] + edge[i].len;
				if (!vis[v]) q.push((node){v, dis[v]});
			}
		}
	}
	printf("%d\n", dis[k * n + T]);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章