codeforces 1025D (区间dp)

                                                                                     Recovering BST

                                                                         Time limit per test   1 second

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.

Input

The first line contains the number of vertices nn (2≤n≤7002≤n≤700).

The second line features nn distinct integers aiai (2≤ai≤1092≤ai≤109) — the values of vertices in ascending order.

Output

If it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than 11, print "Yes" (quotes for clarity).

Otherwise, print "No" (quotes for clarity).

Examples

input

6
3 6 9 18 36 108

output

Yes

input

2
7 17

output

No

input

9
4 8 10 12 15 18 33 44 81

output

Yes

题意:给出n个数,问能否构成一棵二叉搜索树.

思路:dp[i][j][0]代表区间ij能否构成左子树,即i为根往左延伸至j能否构成树(因为i左边的位置的数字都比a[i]小,肯定要去左子树)

同理dp[i][j][1]代表区间ij能够构成右子树,道理跟上面一样.         所以我们可以从小到大遍历每个区间[i,j],枚举区间中的点k作为根,如果dp[k][j][0] == 1&&dp[k][i][1] == 1就说明可以形成以k为根,往左延伸至j作为左子树,往右延伸至i作为右子树的树,这是更新i+1和j-1,如果a[i+1]与a[k]的gcd大于1,那么刚才得到的以k为根的树就可以成为i+1的左子树,即更新dp[i+1][j][0] = 1,同理如果a[j-1]与a[k]的gcd大于1,那么刚才得到的以k为根的树就可以成为j-1的右子树,即更新dp[j-1][i][1] = 1.

代码:

#include
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const int maxn = 1e5+5;

int n;
int a[1234],g[789][789];
int ok[789][789],dp[789][789][2];

int main()
{
	cin>>n;
	for(int i = 1;i<= n;i++)
		scanf("%d",&a[i]);
	for(int i = 1;i<= n;i++)
		for(int j = 1;j< i;j++)
			g[i][j] = g[j][i] = __gcd(a[i],a[j])> 1;
	for(int i = 1;i<= n;i++) dp[i][i][0] = dp[i][i][1] = 1;
	
	for(int i = 1;i<= n;i++)
	{
		for(int j = i;j>= 1;j--)
		{
			for(int k = j;k<= i;k++)
			{
				if(dp[k][j][0]&&dp[k][i][1])
				{
					ok[j][i] = 1;
					dp[j-1][i][1]|= g[j-1][k];
					dp[i+1][j][0]|= g[i+1][k];
				}
			}
		}
	}
	
	if(ok[1][n]) cout<<"Yes"<

 

你可能感兴趣的:(区间dp,CF)