求助大佬,为什么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 四川

相关推荐

11-22 16:49
已编辑
北京邮电大学 Java
美团 质效,测开 n*15.5
点赞 评论 收藏
分享
11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
10-15 03:05
门头沟学院 Java
CADILLAC_:凯文:我的邮箱是死了吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务