「gym104197G」Graph Problem With Small n
\texttt {Problem}
题目描述
给定一个
哈密顿路径:一条恰好经过每个点一次的路径。
数据范围
\texttt {Solution}
不难想到状压dp,有个暴力的做法,
记录每个点
因为每个 dp 值只有 int 表示的 bitset,因为位数少不需要 bitset),这样空间复杂度就是
一般的图论状压都是这样,那么这道题肯定有它的特殊之处,就是哈密顿路径,想想哈密顿路径的性质。
每个点恰好经过一次,这说明什么?最后的路径是一条链,一定有一个点是
也就是说,如果我们能找到
所以,我们只需要找到所有的
因为我们的
总时间复杂度
\texttt {Code}
#include <cstdio>
#define LL long long
#define uLL unsigned LL
namespace Read {
static const int buf_size = 1 << 12;
static const bool use_fread = false;
static unsigned char buf[buf_size];
static int buf_len, buf_pos;
bool isEOF() {
if (buf_pos == buf_len) {
buf_pos = 0; buf_len = fread(buf, 1, buf_size, stdin);
if (buf_pos == buf_len) return true;
}
return false;
}
char readChar() {
if (!use_fread) return getchar();
return isEOF() ? EOF : buf[buf_pos++];
}
LL rint() {
LL x = 0, Fx = 1; char c = readChar();
while (c < '0' || c > '9') { Fx ^= (c == '-'); c = readChar(); }
while ('0' <= c && c <= '9') { x = (x << 3) + (x << 1) + (c ^ 48); c = readChar(); }
return Fx ? x : -x;
}
template <typename T>
void read(T &x) {
x = rint();
}
template <typename T, typename... Ts>
void read(T &x, Ts &...rest) {
read(x);
read(rest...);
}
} using namespace Read;
const int MAX_n = 24;
int n, up;
int v[MAX_n + 5];
int ans[MAX_n + 5];
int dp[(1 << MAX_n) + 5];
char str[MAX_n + 5][MAX_n + 5];
int main() {
#ifdef LOCAL
freopen("DATA.in", "r", stdin);
// freopen("DATA.out", "w", stdout);
#endif
read(n); up = 1 << n;
for (int i = 0; i < n; i++) {
scanf("%s", str[i]);
for (int j = 0; j < n; j++)
if (str[i][j] == '1') v[i] |= (1 << j);
}
dp[1] = 1;
for (int S = 3; S < up; S += 2) {
for (int i = 0; i < n; i++) {
if (S & (1 << i)) {
int T = S ^ (1 << i);
if (v[i] & dp[T]) dp[S] |= (1 << i);
}
}
}
for (int S = 0; S < up; S++)
for (int i = 0; i < n; i++)
if (dp[S] & (1 << i)) ans[i] |= dp[((up - 1) ^ S) | 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%d", (ans[i] >> j) & 1);
printf("\n");
}
return 0;
}