tinycodinglm / cp2 /cp-0039.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
5.95 kB
cp-practice-sim trace
System You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Reply with code only; no explanation.

You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Reply with code only; no explanation.

User 2026-11-08T12:20:03.537Z

Twin Branches

Topic: Hashing and counting (maps/sets) | Difficulty: hard

Problem

A tree has n vertices numbered 1..n and is rooted at vertex 1. Two vertices u != v are twins if the subtree of u and the subtree of v are isomorphic as rooted trees (an isomorphism may reorder the children of every vertex arbitrarily). Count the unordered pairs of twin vertices.

Input

The first line contains n. Each of the next n-1 lines contains two integers a and b, an edge of the tree.

Output

One integer, the number of unordered twin pairs.

Constraints

  • 1 <= n <= 2*10^5
  • the edges form a tree

Examples

Example 1

Input:

markdown
5
1 2
1 3
2 4
3 5

Output:

markdown
2

Note: Vertices 4 and 5 are leaves; vertices 2 and 3 both root a path of two vertices.

Example 2

Input:

markdown
1

Output:

markdown
0

Example 3

Input:

markdown
5
1 2
1 3
1 4
4 5

Output:

markdown
3

Note: The leaves 2, 3 and 5 form 3 pairs; vertex 4 has a child so it matches nothing.

Solve this in Ruby, Java 17, JavaScript (Node.js), one complete program per language. Code only, no explanation.

Assistant 2026-11-08T12:20:05.511Z

Ruby

ruby
data = STDIN.read.split.map(&:to_i)
n = data[0]
adj = Array.new(n + 1) { [] }
(0...n - 1).each do |i|
  a = data[1 + 2 * i]
  b = data[2 + 2 * i]
  adj[a] << b
  adj[b] << a
end
par = Array.new(n + 1, 0)
order = [1]
par[1] = -1
i = 0
while i < order.size
  v = order[i]
  i += 1
  adj[v].each do |w|
    next if w == par[v]
    par[w] = v
    order << w
  end
end
kids = Array.new(n + 1) { [] }
id = Array.new(n + 1, 0)
dict = {}
cls = []
order.reverse_each do |v|
  key = kids[v].sort
  c = dict[key]
  if c.nil?
    c = cls.size
    dict[key] = c
    cls << 0
  end
  cls[c] += 1
  id[v] = c
  kids[par[v]] << c if par[v] > 0
end
puts cls.sum { |c| c * (c - 1) / 2 }

Java 17

java
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer st = new StreamTokenizer(new BufferedInputStream(System.in));
        st.nextToken();
        int n = (int) st.nval;
        int[] head = new int[n + 1], nxt = new int[2 * n], to = new int[2 * n];
        Arrays.fill(head, -1);
        int ec = 0;
        for (int i = 0; i < n - 1; i++) {
            st.nextToken(); int a = (int) st.nval;
            st.nextToken(); int b = (int) st.nval;
            to[ec] = b; nxt[ec] = head[a]; head[a] = ec++;
            to[ec] = a; nxt[ec] = head[b]; head[b] = ec++;
        }
        int[] par = new int[n + 1], order = new int[n];
        par[1] = -1;
        order[0] = 1;
        int sz = 1;
        for (int i = 0; i < sz; i++) {
            int v = order[i];
            for (int e = head[v]; e >= 0; e = nxt[e]) {
                int w = to[e];
                if (w == par[v]) continue;
                par[w] = v;
                order[sz++] = w;
            }
        }
        List<List<Integer>> kids = new ArrayList<>();
        for (int i = 0; i <= n; i++) kids.add(new ArrayList<>());
        HashMap<String, Integer> dict = new HashMap<>();
        List<Long> cls = new ArrayList<>();
        for (int i = n - 1; i >= 0; i--) {
            int v = order[i];
            List<Integer> k = kids.get(v);
            Collections.sort(k);
            StringBuilder sb = new StringBuilder();
            for (int x : k) sb.append(x).append(',');
            String key = sb.toString();
            Integer c = dict.get(key);
            if (c == null) {
                c = cls.size();
                dict.put(key, c);
                cls.add(0L);
            }
            cls.set(c, cls.get(c) + 1);
            if (par[v] > 0) kids.get(par[v]).add(c);
        }
        long ans = 0;
        for (long c : cls) ans += c * (c - 1) / 2;
        System.out.println(ans);
    }
}

JavaScript (Node.js)

javascript
const t = require('fs').readFileSync(0, 'utf8').split(/\s+/).filter(x => x).map(Number);
const n = t[0];
const adj = Array.from({ length: n + 1 }, () => []);
for (let i = 0; i < n - 1; i++) {
  const a = t[1 + 2 * i], b = t[2 + 2 * i];
  adj[a].push(b);
  adj[b].push(a);
}
const par = new Array(n + 1).fill(0);
par[1] = -1;
const order = [1];
for (let i = 0; i < order.length; i++) {
  const v = order[i];
  for (const w of adj[v]) {
    if (w === par[v]) continue;
    par[w] = v;
    order.push(w);
  }
}
const kids = Array.from({ length: n + 1 }, () => []);
const dict = new Map();
const cls = [];
for (let i = n - 1; i >= 0; i--) {
  const v = order[i];
  const k = kids[v].sort((x, y) => x - y);
  const key = k.join(',');
  let c = dict.get(key);
  if (c === undefined) {
    c = cls.length;
    dict.set(key, c);
    cls.push(0);
  }
  cls[c]++;
  if (par[v] > 0) kids[par[v]].push(c);
}
let ans = 0;
for (const c of cls) ans += c * (c - 1) / 2;
console.log(String(ans));