最小斯坦纳树,WA50
查看原帖
最小斯坦纳树,WA50
50925
EternalEpic楼主2020/7/29 23:36
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
const int Maxn = 15, Maxm = 1 << 11;
int n, m, k, a[Maxn * Maxn], ans[Maxn][Maxn], dp[Maxn * Maxn][Maxm], cnt;
typedef pair < pair <int, int>, int > pii; pii pre[Maxn * Maxn][Maxm];

struct state {
	int x, y, d;
	state(void) { x = y = d = 0; }
	state(int _x, int _y, int _d) : x(_x), y(_y), d(_d) {}
	inline bool operator < (const state&rhs) const { return d > rhs.d; }
}; priority_queue <state> q; bool vis[Maxn][Maxn];

inline bool vaild(int x, int y) { return x >= 1 && y >= 1 && x <= n && y <= m; }
inline void Dijkstra(int s) {
	Ms(vis, false);
	while (!q.empty()) {
		int x = q.top().x, y = q.top().y; q.pop();
		if (vis[x][y]) continue; vis[x][y] = true;
		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i], ny = y + dy[i];
			if (vaild(nx, ny) && dp[(nx - 1) * n + ny][s] > dp[(x - 1) * n + y][s] + a[(nx - 1) * n + ny]) {
				dp[(nx - 1) * n + ny][s] = dp[(x - 1) * n + y][s] + a[(nx - 1) * n + ny];
				q.push(state(nx, ny, dp[(nx - 1) * n + ny][s])); pre[(nx - 1) * n + ny][s] = Mp(Mp(x, y), s);
			}
		}
	}
}

#define coor(u) ((u.first - 1) * n + u.second)
inline void findpaths(pair <int, int> u, int s) {
	if (!pre[coor(u)][s].second) return;
	ans[u.first][u.second] = 1;
	if (pre[coor(u)][s].first == u) findpaths(u, s ^ pre[coor(u)][s].second);
	findpaths(pre[coor(u)][s].first, pre[coor(u)][s].second);
}

int fx, fy, pos;
signed main(void) {
//	file("");
	read(n), read(m); Ms(dp, 0x3f);
	for (int i = 1; i <= n; i++)
	for (int j = 1; j <= m; j++) {
		read(a[++cnt]);
		if (a[cnt] == 0) { ++k;
			dp[cnt][1 << k - 1] = 0;
			pos = cnt; fx = i; fy = j;
		}
	}
	
	for (int s = 1; s < 1 << k; s++) {
		for (int x = 1; x <= n; x++)
		for (int y = 1; y <= m; y++) { int i = (x - 1) * n + y;
			for (int subset = s & (s - 1); subset; subset = (subset - 1) & s)
				if (dp[i][s] > dp[i][subset] + dp[i][s ^ subset] - a[i]) {
					dp[i][s] = dp[i][subset] + dp[i][s ^ subset] - a[i];
					pre[i][s] = Mp(Mp(x, y), subset);
				}
			if (dp[i][s] != 0x3f3f3f3f) q.push(state(x, y, dp[i][s]));
		} Dijkstra(s);
	} writeln(dp[pos][(1 << k) - 1]); findpaths(Mp(fx, fy), (1 << k) - 1);
	
	for (int i = 1; i <= n; i++)
	for (int j = 1; j <= m; j++) {
		if (!a[(i - 1) * n + j]) putchar('x');
		else putchar(ans[i][j] ? 'o' : '_');
		if (j == m) putchar('\n');
	}
//	fwrite(pf, 1, o1 - pf, stdout);
	return 0;
}

/**/

谁知道哪里错了,WA的输出了0x3f3f3f3f

2020/7/29 23:36
加载中...