D. Recovering BST(dp+记忆化搜索)

40 篇文章 0 订阅
26 篇文章 0 订阅

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个数,按升序给出,组成一颗二叉树,每两个相连节点之间必须有公约数。问是否能够组成这棵树。

思路:

预处理一下互质的数。

枚举根,dfs左右区间,dp+记忆化搜索看是否能找出一组解。

代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=800;
const int INF=1e9+7;
const int mod=1e9+7;
int a[maxn];
int zh[maxn][maxn];
int dp[maxn][maxn][2];
int vis[maxn][maxn][2];

int dfs(int l,int r,int k)
{
    if(l>r)return 1;
    if(vis[l][r][k])return dp[l][r][k];
    int flag;
    if(!k)flag=r+1;
    else flag=l-1;
    int flag1=0;
    for(int i=l;i<=r;i++)
    {
        if(!zh[i][flag]&&dfs(l,i-1,0)&&dfs(i+1,r,1))
        {
            flag1=1;
            break;
        }
    }
    vis[l][r][k]=1;
    return dp[l][r][k]=flag1;
}
long long gcd(long long m, long long n)
{
    while(m>0)
    {
        long long c = n % m;
        n = m;
        m = c;
    }
    return n;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=i;j<=n;j++)
        {
            if(gcd(a[i],a[j])==1)
            {
                zh[i][j]=zh[j][i]=1;
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(dfs(1,i-1,0)&&dfs(i+1,n,1))
        {
            printf("Yes\n");
            return 0;
        }
    }

    printf("No\n");
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值