容易想到设f[i][j][k]为i~j区间以k为根是否能构成bst。这样是O(n4)的。考虑将状态改为f[i][j][0/1]表示i~j区间以i-1/j+1为根能否构成bst。显然如果是i-1作为根的话i~j区间都在它的右子树,所以转移时枚举右子树的根并判断是否合法,j+1类似。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<‘0‘||c>‘9‘) {if (c==‘-‘) f=-1;c=getchar();} while (c>=‘0‘&&c<=‘9‘) x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 710 int n,a[N]; bool flag[N][N],f[N][N][2]; int gcd(int n,int m){return m==0?n:gcd(m,n%m);} int main() { #ifndef ONLINE_JUDGE freopen("d.in","r",stdin); freopen("d.out","w",stdout); const char LL[]="%I64d\n"; #else const char LL[]="%lld\n"; #endif 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) flag[i][j]=1; for (int i=1;i<=n+1;i++) f[i][i-1][0]=f[i][i-1][1]=1; for (int k=1;k<=n;k++) for (int i=1;i<=n-k+1;i++) { int j=i+k-1; for (int d=i;d<=j;d++) if (f[i][d-1][1]&&f[d+1][j][0]) { if (flag[i-1][d]) f[i][j][0]=1; if (flag[j+1][d]) f[i][j][1]=1; } } for (int i=1;i<=n;i++) if (f[1][i-1][1]&&f[i+1][n][0]) {cout<<"Yes";return 0;} cout<<"No"; return 0; }
原文地址:https://www.cnblogs.com/Gloid/p/9780193.html
时间: 2024-10-09 19:43:50