Recovering BST

Codeforces Round #505 D. Recovering BST

题目链接:http://codeforces.com/problemset/problem/1025/D

题意:给定一个长度为n(<= 700)的序列问是否能用这些数字构造出一颗二叉排序树,使得其每条边连接的两个点之间的gcd(最大公约数)>1

做法:对序列排序,我们容易想到枚举每一条边判断是否合法,但是显然很暴力。考虑到,当我们确定了一条边时,如(u,v)(假设v为父节点)那么以u为根的子树所管理的区间是可以被确定的,就是[1,v - 1],利用这一点进行区间dp

f[i][j][k]表示从i到j这个区间以k为根是否可行,方程也易得

但是这个题很丧心地卡了n^3的空间,用bitset压缩

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define  LONG long long
const int INF=0x3f3f3f3f;
const int  MOD=1e9+ 7;
const double PI=acos(-1.0);
#define clrI(x) memset(x,-1,sizeof(x))
#define clr0(x) memset(x,0,sizeof x)
#define clr1(x) memset(x,INF,sizeof x)
#define clr2(x) memset(x,-INF,sizeof x)
#define EPS 1e-10
const int MAXN = 700 + 10;
int a[MAXN];
bitset f[MAXN][MAXN];
bool can[MAXN][MAXN];
int gcd(int a, int b) {
    int c = a % b;
    while (c) {
        a = b;
        b = c;
        c = a % b;
    }
    return b;
}
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++ i) cin >> a[i];
    sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; ++ i) {
        for (int j = i; j <= n; ++ j)
            if (gcd(a[i], a[j]) > 1) can[i][j] = true;
    }
    for (int i = 1; i < n; ++ i) {
        if (can[i][i + 1]) {
            f[i][i + 1][i] = f[i][i + 1][i + 1] = 1;
        }
    }
    for (int l = 3; l <= n; ++ l) {
        for (int i = 1; i <= n; ++ i) {
            int j = i + l - 1;
            if (j > n) break;
            for (int k = i; k <= j; ++ k) {
                if (k == i) {
                    for (int l = i + 1; l <= j; ++ l) {
                        f[i][j][k] = (can[k][l] & f[i + 1][j][l]) | f[i][j][k];
                    }
                } else if (k == j) {
                    for (int l = i; l < j; ++ l) {
                        f[i][j][k] = (can[l][k] & f[i][j - 1][l]) | f[i][j][k];
                    }
                } else {
                    f[i][j][k] = (f[i][k][k] & f[k][j][k]) | f[i][j][k];
                }
            }
        }
    }
    for (int i = 1; i <= n; ++ i) {
        if (f[1][n][i]) return cout << "Yes" << endl, 0;
    }
    cout << "No" <

你可能感兴趣的:(DP,CF,树上问题)