CF1025D Recovering BST

题目描述:

Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!

Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset.

To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed 11 .

Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here.

题目大意:

给定一个单调不减的序列,定义一颗合格的二叉排序树是有连边的节点上的权值不互质,判断给定的序列是否能表示一颗合格的二叉排序树中序遍历的权值序列。

tips:二叉排序树的中序遍历权值序列单调不减。

算法标签:记忆化搜索,bitset

思路:

用f[l][r][rt]表示,表示对于区间l,r以rt为根的合法性。因为数组存不下,所以我们考虑用bitset来存dp值。记忆化搜索转移。

(感觉效率应该过不去,但是AC了.....可能是水过的吧)

以下代码:

#include<bits/stdc++.h>
#define il inline
#define _(d) while(d(isdigit(ch=getchar())))
using namespace std;
const int N=701;
int n,g[N][N],a[N];bitset<N> f[N][N],vis[N][N];
il int read(){
    int x,f=1;char ch;
    _(!)ch=='-'?f=-1:f;x=ch^48;
    _()x=(x<<1)+(x<<3)+(ch^48);
    return f*x;
}
il int gcd(int x,int y){
    return x==0?y:gcd(y%x,x);
}
il bool search(int l,int r,int rt){
    if(l>r)return 1;if(l==r)return !g[l][rt];
    if(vis[l][r][rt])return f[l][r][rt];
    for(int i=l;i<=r;i++){
        if(!g[i][rt]&&search(l,i-1,i)&&search(i+1,r,i)){
            f[l][r][rt]=1;break;
        }
    }
    vis[l][r][rt]=1;return f[l][r][rt];
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)a[i]=read();
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++){
        if(gcd(a[i],a[j])==1)g[i][j]=1;
    }
    if(search(1,n,0))puts("Yes");else puts("No");
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Jessie-/p/10362424.html