洛谷 P4568 [JLOI2011]飞行路线

题目描述###

Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。

Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?

输入输出格式
输入格式:

数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号。
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。

输出格式:

只有一行,包含一个整数,为最少花费。

输入输出样例
输入样例#1:
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100

输出样例#1:

8

题解###

简单的最短路+dp 我竟然没有一遍切
dp[i][j]表示到编号为i时,用了j次免费机会的最少花费

转移十分显然

Code###

#include<bits/stdc++.h>
#define LL long long
#define RG register
using namespace std;

inline int gi() {
    int f = 1, s = 0;
    char c = getchar();
    while (c != '-' && (c < '0' || c > '9')) c = getchar();
    if (c == '-') f = -1, c = getchar();
    while (c >= '0' && c <= '9') s = s*10+c-'0', c = getchar();
    return f == 1 ? s : -s;
}

const int N = 10010, M = 50010;

struct node {
	int to, next, w;
}g[M<<1];
int last[N], gl;
inline void add(int z, int y, int x) {
	g[++gl] = (node) {y, last[x], z};
	last[x] = gl;
	g[++gl] = (node) {x, last[y], z};
	last[y] = gl;
	return ;
}

queue<int> q;
int f[N][15];
bool vis[N];
int main() {
	int n = gi(), m = gi(), k = gi(), s = gi(), t = gi();
	for (int i = 1; i <= m; i++) add(gi(), gi(), gi());
	q.push(s);
	memset(f, 127/3, sizeof(f));
	f[s][0] = 0;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		for (int i = last[u]; i; i = g[i].next) {
			int v = g[i].to;
			for (int j = 0; j <= k; j++) {
				if (j > 0 && f[v][j] > f[u][j-1]) {
					f[v][j] = f[u][j-1];
					if (!vis[v]) q.push(v), vis[v] = 1;
				}
				if (f[u][j] + g[i].w < f[v][j]) {
					f[v][j] = f[u][j] + g[i].w;
					if (!vis[v]) q.push(v), vis[v] = 1;
				}
			}
		}
		vis[u] = 0;
	}
	int ans = 2147483647;
	for (int i = 0; i <= k; i++)
		ans = min(ans, f[t][i]);
	printf("%d
", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/zzy2005/p/9843042.html