题目链接:http://codeforces.com/contest/1025/problem/D
题意:给了一组数,最大公约数不为1的两个数可以连一条边,问能否构造出一棵二叉搜索树
分析:区间dp,r[i][j]表示i-j区间的数能否作为以第i-1个数为根的右子树,l[i][j]表示i-j区间的数能否作为以第i-1个数为根的左子树,注意用相邻的两个数赋初值
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 710;
int gcd(int x,int y)
{
if(y == 0)return x;
else return gcd(y,x % y);
}
int a[maxn],G[maxn][maxn],l[maxn][maxn],r[maxn][maxn];
int main()
{
int n;
cin>>n;
for(int i = 1; i <= n; i++)
cin>>a[i];
if(n == 2)
{
if(gcd(a[1],a[2]) > 1)
{
printf("Yes\n");
}
else printf("No\n");
return 0;
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i != j)
{
G[i][j] = (gcd(a[i],a[j]) > 1);
}
}
}
for(int i = 1; i < n; i++)
{
if(G[i][i + 1])
l[i][i] = 1;
if(G[i][i + 1])
r[i + 1][i + 1] = 1;
}
for(int len = 1; len <= n - 1; len++)
{
for(int i = 1; i <= n - len; i++)
{
int j = i + len;
for(int mid = i; mid <= j; mid++)
{
if(i == mid)
{
if(r[mid + 1][j] && G[i - 1][mid])
r[i][j] = 1;
if(r[mid + 1][j] && G[mid][j + 1])
l[i][j] = 1;
}
else if(j == mid)
{
if(l[i][mid - 1] && G[i - 1][mid])
r[i][j] = 1;
if(l[i][mid - 1] && G[mid][j + 1])
l[i][j] = 1;
}
else
{
if(l[i][mid - 1] && r[mid + 1][j])
{
if(G[i - 1][mid])
r[i][j] = 1;
if(G[mid][j + 1])
l[i][j] = 1;
}
}
}
}
}
for(int i = 1; i <= n; i++)
{
if(i == 1 && r[i + 1][n])
{
//printf("%d\n",i);
printf("Yes\n");
return 0;
}
else
{
if(l[1][i - 1] && r[i + 1][n])
{
printf("Yes\n");
return 0;
}
}
}
printf("No\n");
return 0;
}