privateintsquareFree(int x) { intres=1; for (inti=2; i * i <= x; i++) { if (x % i == 0) { intcnt=0; while (x % i == 0) { x /= i; cnt++; } if (cnt % 2 != 0) { res *= i; } } } if (x > 1) { res *= x; } return res; }
publicSolutions2(){ FastReadersc=newFastReader(); n = sc.nextInt(); a = newint[n + 1]; f = newint[n + 1]; for (inti=1; i <= n; i++) { a[i] = sc.nextInt(); f[i] = squareFree(a[i]); }
tree = newArrayList[n + 1]; for (inti=1; i <= n; i++) tree[i] = newArrayList<>(); for (inti=1; i < n; i++) { intu= sc.nextInt(); intv= sc.nextInt(); tree[u].add(v); tree[v].add(u); }
if (!visited) { stack.push(newObject[]{u, fa, true}); List<Integer> children = newArrayList<>(); for (int v : tree[u]) { if (v != fa) { children.add(v); } } // 逆序压入,以保持原来的处理顺序 for (inti= children.size() - 1; i >= 0; i--) { intv= children.get(i); stack.push(newObject[]{v, u, false}); } } else { List<Integer> children = newArrayList<>(); for (int v : tree[u]) { if (v != fa) { children.add(v); } } if (children.size() >= 2) { Map<Integer, Integer> cnt = newHashMap<>(); for (int v : children) { intsf= f[v]; cnt.put(sf, cnt.getOrDefault(sf, 0) + 1); } for (int c : cnt.values()) { if (c > 1) { ans += c - 1; } } } } } System.out.println(ans); }