其他分享
首页 > 其他分享> > 【Luogu P4568】[JLOI2011]飞行路线

【Luogu P4568】[JLOI2011]飞行路线

作者:互联网

链接:

洛谷

题目大意:

在一张图上,有 \(k\) 条边可以免代价,求 \(s\) 到 \(t\) 的最短路。

正文:

这是分层图最短路板子。建 \(k\) 层图,上一层到本次的边权为 \(0\)。很好理解。

代码:

const int N = 1e6 + 10, M = 5e6 + 10;

inline ll Read() {
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

int n, m, k, s, t;
struct edge {
	int to, nxt, val;
}e[M]; 
int head[N], tot;
void add(int u, int v, int w) {
	e[++tot] = (edge) {v, head[u], w}, head[u] = tot;
}

struct node {
	int val, key;
	bool operator < (const node &a) const {
		return key > a.key;
	}
};
priority_queue <node> q;
int dis[N];
bool vis[N];
void dij() {
	memset (dis, 127 / 3, sizeof dis);
	dis[s] = 0;
	q.push((node){ s, 0 });
	while (!q.empty()) {
		int u = q.top().val; q.pop();
		if (vis[u]) continue; vis[u] = 1;
		for (int i = head[u]; i; i = e[i].nxt) {
			if (!vis[e[i].to] && dis[u] + e[i].val < dis[e[i].to]) {
				dis[e[i].to] = dis[u] + e[i].val;
				q.push((node){ e[i].to, dis[u] + e[i].val });
			}
		}
	}
}

int main() {
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);
	n = Read(), m = Read(), k = Read();
	s = Read(), t = Read();
	for (int i = 1; i <= m; i++) {
		int u = Read(), v = Read(), w = Read();
		add (u, v, w), add (v, u, w);
		for (int j = 1; j <= k; j++) {
			add (u + j * n, v + j * n, w);
			add (v + j * n, u + j * n, w);
			add (u + (j - 1) * n, v + j * n, 0);
			add (v + (j - 1) * n, u + j * n, 0);
		}
	}
	dij (); 
	int ans = 1e9;
	for (int i = 0; i <= k; i++) ans = min (ans, dis[i * n + t]);
	printf ("%d", ans); 
	return 0;
}

标签:val,JLOI2011,vis,Read,Luogu,P4568,int,getchar,dis
来源: https://www.cnblogs.com/GJY-JURUO/p/15570402.html