给定一个序列,问这个序列是否能够构成一个二叉搜索树,使得任一边连接的点的gcd大于1
区间dp
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 710;
int A[maxn];
bool G[maxn][maxn];
bool dp[maxn][maxn][2];
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
int main() {
int n; scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &A[i]);
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) {
G[i][j] = (gcd(A[i], A[j]) > 1);
}
for (int len = 1; len <= n; len++) {
for (int l = 1, r = l + len - 1; l + len - 1 <= n; l++, r++) {
for (int m = l; m <= r; m++) {
bool flag = true;
if (l == m) {
flag &= true;
} else {
flag &= dp[l][m - 1][0];
}
if (m == r) {
flag &= true;
} else {
flag &= dp[m + 1][r][1];
}
if (flag) {
dp[l][r][1] |= G[m][l - 1];
dp[l][r][0] |= G[m][r + 1];
}
}
}
}
for (int i = 1; i <= n; i++) {
bool tag = true;
if (i == 1) {
tag &= true;
} else {
tag &= dp[1][i - 1][0];
}
if (i == n) {
tag &= true;
} else {
tag &= dp[i + 1][n][1];
}
if (tag) {
puts("Yes"); return 0;
}
}
puts("No");
return 0;
}
原文地址:https://www.cnblogs.com/xFANx/p/9513580.html
时间: 2024-10-21 07:36:41