CodeM4

来源:互联网 发布:nginx conf配置详解 编辑:程序博客网 时间:2024/06/11 03:05

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<>();
}

原创粉丝点击