CodeM4

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BCode4 {
public static int max = 0;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int num = Integer.parseInt(sc.nextLine());
    List<int[]> list = new ArrayList<int[]>();
    for (int i = 0; i < num - 1; i++) {
        int[] charArray = new int[2];
        String[] split = sc.nextLine().split(" ");
        charArray[0] = Integer.parseInt(split[0]);
        charArray[1] = Integer.parseInt(split[1]);
        list.add(charArray);
    }
    String[] split = sc.nextLine().split(" ");
    tree[] trees = new tree[num];
    for (int i = 0; i < num; i++) {
        tree t = new tree();
        t.value = Integer.parseInt(split[i]);
        trees[i]=t;
    }
    for (int i = 0; i < num - 1; i++) {
        for (int j = 0; j < list.size(); j++) {
            int[] ks = list.get(j);
            if(ks!=null&&ks.length>0){
            if (ks[0] == i+1) {
                trees[i].next.add(trees[ks[1] - 1]);
            }
            }
        }
    }
    getNum(trees[0]);
    System.out.println(max);
}


public static List<Integer> l = new ArrayList<Integer>();
//深度遍历
public static void getNum(tree t) {
    l.add(t.value);
    if (t.next.isEmpty()) {
        if(l.size()>2){
        if (gys(l)) {
            if (max < l.size()) {
                max = l.size();
                return;
            }
        }
        }
        return;
    }
    for (int i = 0; i < t.next.size(); i++) {
        t=t.next.get(i);
        getNum(t);
    }
    l.remove(l.size()-1);
}
public static int gcd(int n ,int m){
    if (n<m)
    {
        n=m+n;
        m=n-m;
        n=n-m;
    }
    if (m==0) return n;
    return gcd(m,n%m);
}

public static boolean gys(List<Integer> l) {
    int a=l.get(0);
    int b=l.get(1);
    int c= gcd(a,b);
    int i ;
    for (i = 2; i < l.size(); i++) {
        c=gcd(c, l.get(i));
    }
    if(c>1){
        return true;
    }
    return false;
}

}

class tree {
int value;
ArrayList next = new ArrayList<>();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值