题目描述
给定一个 个点的无向图,对每对二元组 ,判断是否存在一条 的哈密顿路径。
哈密顿路径:一条恰好经过每个点一次的路径。
数据范围
不难想到状压dp,有个暴力的做法, 表示从 出发,经过了点集 ,终点为 是否可行,时间复杂度是 ,空间复杂度 。
记录每个点 的相邻点的点集 ,上面的状态就可以直接枚举可能的终点,用 是否有值来 判断其可不可能成为终点,时间复杂度可以优化成 ,空间复杂度不变。
因为每个 dp 值只有 两种情况,不妨把 这一维放入 dp 值中,即 表示从 出发,经过了点集 ,能到达的终点的集合(这个方法很常见,类似高维前缀和,相当于能用 int 表示的 bitset,因为位数少不需要 bitset),这样空间复杂度就是 的。
一般的图论状压都是这样,那么这道题肯定有它的特殊之处,就是哈密顿路径,想想哈密顿路径的性质。
每个点恰好经过一次,这说明什么?最后的路径是一条链,一定有一个点是 (记点的标号为 ),它会把这条路径分成两部分。由于是无向图,不妨考虑从 出发向两端走,如果这两条路径不经过同一个点(除了起点 ),并且和起来经过了 个点,是不是就说明这两条路径的终点 和 之间存在一条哈密顿路径。
也就是说,如果我们能找到 经过的点集 , 经过的点集 ,使得 (设 为全集),那么 的答案就为 。
所以,我们只需要找到所有的 ,然后枚举 ,此时 ,如果 ,则 的答案是 ,具体实现可以用 表示起点为 答案为 的终点 的集合(和上面 dp 去维的方法一样)。那么转移时,就是再枚举 ,如果 在集合 里,就用 更新 ,总时间复杂度 。
因为我们的 实际只有一维(),所以空间复杂度是 的,转移时枚举 和可能的终点 ,时间复杂度 。
总时间复杂度 ,空间复杂度 ,可以通过本题。
#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;
}