求助大佬,为什么D题只能过20%的数据

import java.io.*;
import java.util.Arrays;
  
public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer sk = new StreamTokenizer(br);
    static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    static long w[];
    static int h[], ne[], idx, e[], n;
    static int color[];
    static int res = 0;
    static boolean []st;
    public static void main(String[] args) throws Exception {
        n = nextInt();
        w = new long[n + 10];
        h = new int[n + 10];
        ne = new int[2 * n + 10];
        e = new int[2 * n + 10];
        color = new int[n + 10];
        st = new boolean[n + 10];
        Arrays.fill(color, -1);
        Arrays.fill(st, false);
        for (int i = 1; i <= n; i ++ ) {
            w[i] = nextLong();
        }
  
        Arrays.fill(h, -1);
        for (int i = 0; i < n - 1; i ++ ) {
            int a = nextInt(), b = nextInt();
            add(a, b);
            add(b, a);
        }
  
        for (int i = 1; i <= n; i ++ ) {
            dfs(i);
        }
          
  
        pw.println(res);
        pw.flush();
    }
  
    private static void dfs(int u) {
        if (color[u] != -1) {
            return ;
        }
        color[u] = 1;
        for (int i = h[u]; i != -1; i = ne[i]) {
            int j = e[i];
            if (color[j] != -1) {
                continue;
            }
            if (is_sqrt(w[u] * w[j])) {
                color[u] = 1;
                color[j] = 1;
                res += 2;
            }
             
            dfs(j);
        }
    }
  
    private static boolean is_sqrt(long u) {
        long x = (long)Math.sqrt(u);
        return x * x == u;
    }
  
    private static void add(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx;
        idx ++ ;
    }
  
  
    public static int nextInt() throws Exception {
        sk.nextToken();
        return (int)sk.nval;
    }
    public static long nextLong() throws Exception {
        sk.nextToken();
        return (long) sk.nval;
    }
  
    public static String nextString() throws Exception {
        sk.nextToken();
        return sk.sval;
    }
}

全部评论
这应该拿树形dp做吧
点赞 回复 分享
发布于 2023-08-20 22:21 四川

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
vegetable_more_exercise:1-1.5万,没错啊,最少是1人民币,在区间内
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务