zoukankan      html  css  js  c++  java
  • CodeForces

    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 (2n7002≤n≤700).

    The second line features nn distinct integers aiai (2ai1092≤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

    题意:给定一个序列,如果两个数gcd不为1,则可以连边,现在问连边是否可以构造二叉搜索树(左子树的节点值都小于本节点,右子数都大于)。

    思路:没想到。看了题解。题解是,区间DP。L[i][j]表示区间(i,j)是否可以作为j+1的左子树,R[i][j]同理。对于L[i][j],我们要找Mid,使得L[i,Mid-1]==true,且R[Mid+1,j]=true,且gcd(a[Mid],a[j+1])>1;此时L[i][j]=1; R数组同理。

    (因为大小右分组的关系,那么就用区间来搞。。。好事没毛病。

    #include<bits/stdc++.h>
    #define rep(i,a,b) for(int i=a;i<=b;i++)
    using namespace std;
    const int maxn=710;
    int a[maxn],g[maxn][maxn],l[maxn][maxn],r[maxn][maxn];
    int main()
    {
        int N,i,j;
        scanf("%d",&N);
        rep(i,1,N) scanf("%d",&a[i]);
        rep(i,1,N) rep(j,1,N) if(i!=j) g[i][j]=(__gcd(a[i],a[j])>1);
        rep(i,0,N-1){
            rep(L,1,N-i){
                int R=i+L;
                rep(Mid,L,R){
                    if((L<=Mid-1?l[L][Mid-1]:1)&&(R>=Mid+1?r[Mid+1][R]:1)){
                        if(g[L-1][Mid]) r[L][R]=1;
                        if(g[Mid][R+1]) l[L][R]=1;
                    }
                }
            }
        }
        rep(i,1,N){
           if((1<=i-1?l[1][i-1]:1)&&(N>=i+1?r[i+1][N]:1))
             return puts("Yes"),0;
        }
        puts("No");
        return 0;
    }
  • 相关阅读:
    iOS9--适配系列教程(原文/译文)
    电梯调度设计思路及算法
    10大高频率单词筛选
    html知识点总结
    关于博客
    Java构造器内部的多态方法
    Java初学者必学的六大Java语言要点
    Java中的length字段和length()方法
    Java学习有方法有捷径
    Java 分隔符函数split的使用注意事项
  • 原文地址:https://www.cnblogs.com/hua-dong/p/9539085.html
Copyright © 2011-2022 走看看