D. Recovering BST(dfs记忆化搜索)

D. Recovering BST

http://codeforces.com/contest/1025/problem/D

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

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 1

.

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 n

(2≤n≤700

).

The second line features n

distinct integers ai (2≤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 1

, print "Yes" (quotes for clarity).

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

Examples

Input

Copy

6
3 6 9 18 36 108

Output

Copy

Yes

Input

Copy

2
7 17

Output

Copy

No

Input

Copy

9
4 8 10 12 15 18 33 44 81

Output

Copy

Yes

Note

The picture below illustrates one of the possible trees for the first example.

The picture below illustrates one of the possible trees for the third example.

 

题意:给了n个点的权值。如果gcd大于1就可以相连,否则不能。

让构造一个二叉搜索树(左儿子都小于根节点,右儿子都大于根节点),问能不能。

思路:利用区间dp的思想进行记忆化搜索。

用vis[l][r][k]表示l——r这段区间作为k(左或右)儿子是否dfs过。

dp[l][r][k]代表是否可行。

算是区间dp的思想吧。

其实就是爆搜。

代码:

#include
using namespace std;
const int maxn=800;
int G[maxn][maxn],vis[maxn][maxn][4],dp[maxn][maxn][4];
int a[maxn];
int dfs(int rt,int l,int r,int k){
    int flag=0;
    if(vis[l][r][k])
        return dp[l][r][k];
    if(l>r)///如果是等于的话还不能退出,还要看当前节点和根节点是否有边。
        return 1;
    for(int i=l;i<=r;i++){///在l——r区间里以i为根节点
        if(G[i][rt] &&dfs(i,l,i-1,0) && dfs(i,i+1,r,1)){
            flag=1;
            break;
        }
    }
    vis[l][r][k]=1;///无论根是谁,这块区间我搜过了就是搜过了
    dp[l][r][k]=flag;
    return flag;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
    memset(G,0,sizeof(G));
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j)
                continue;
            if(__gcd(a[i],a[j])!=1){
                G[i][j]=1;
            }
        }
    }
   /// cout<<"&&:"<

 

你可能感兴趣的:(DP_区间dp,DFS,思维)