【BZOJ1097】[POI2007]旅游景点atr【最短路】【状压DP】【记忆化搜索】

k很小,所以可以状压。


先预处理出以1到k + 1为出发点的最短路,然后记忆化搜索。


/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <utility>

using namespace std;

typedef pair<int, int> pii;

const int maxn = 20005, maxm = 200005, maxk = 21, maxs = 1 << (maxk - 1), inf = 0x3f3f3f3f;

int n, m, k, head[maxn], cnt, dis[maxk][maxn], state[maxs], dp[maxk][maxs];

priority_queue<pii, vector<pii>, greater<pii> > q;

struct _edge {
	int v, w, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v, int w) {
	g[cnt] = (_edge){v, w, head[u]};
	head[u] = cnt++;
}

inline void dijkstra(int s) {
	while(!q.empty()) q.pop();
	for(int i = 0; i <= n; i++) dis[s][i] = inf;
	dis[s][s] = 0;
	q.push(pii(0, s));

	while(!q.empty()) {
		pii x = q.top(); q.pop();
		int u = x.second;
		if(dis[s][u] < x.first) continue;
		for(int i = head[u]; ~i; i = g[i].next) if(dis[s][g[i].v] > dis[s][u] + g[i].w) {
			dis[s][g[i].v] = dis[s][u] + g[i].w;
			q.push(pii(dis[s][g[i].v], g[i].v));
		}
	}
}

inline int dfs(int x, int s) {
	if(dp[x][s]) return dp[x][s];
	if(s == (1 << k) - 1) return dis[x][n - 1];
	dp[x][s] = inf;
	for(int i = 1; i <= k; i++) if((s & state[i]) == state[i])
		dp[x][s] = min(dp[x][s], dis[x][i] + dfs(i, s | (1 << (i - 1))));
	return dp[x][s];
}

int main() {
	n = iread(); m = iread(); k = iread();
	for(int i = 0; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i <= m; i++) {
		int x = iread(), y = iread(), w = iread(); x--; y--;
		add(x, y, w); add(y, x, w);
	}
	m = iread();
	for(int i = 1; i <= m; i++) {
		int x = iread(), y = iread(); x--; y--;
		state[y] |= 1 << (x - 1);
	}

	for(int i = 0; i <= k; i++) dijkstra(i);
	printf("%d\n", dfs(0, 0));
	return 0;
}


你可能感兴趣的:(最短路,记忆化搜索,状压dp)