File size: 5,952 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "cp-practice-sim", "id": "cp-0039", "name": "Twin Branches", "mode": "chat", "topic": "Hashing and counting (maps/sets)", "difficulty": "hard", "tags": ["tree canonical form", "hash-consing", "isomorphism", "counting"], "explanation_mode": "none", "tool_scenario": "none", "expected_recovery": "N/A - no fault injected.", "languages": ["ruby", "java", "javascript"], "unexecuted_languages": [], "time_complexity": "O(n log n)", "space_complexity": "O(n)"}
{"type": "message", "message": {"role": "system", "content": "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. ", "timestamp": 1794140401700}}
{"type": "message", "message": {"role": "user", "content": "# Twin Branches\n\nTopic: Hashing and counting (maps/sets) | Difficulty: hard\n\n## Problem\nA 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.\n\n## Input\nThe first line contains n. Each of the next n-1 lines contains two integers a and b, an edge of the tree.\n\n## Output\nOne integer, the number of unordered twin pairs.\n\n## Constraints\n- 1 <= n <= 2*10^5\n- the edges form a tree\n\n## Examples\n### Example 1\nInput:\n```\n5\n1 2\n1 3\n2 4\n3 5\n```\nOutput:\n```\n2\n```\nNote: Vertices 4 and 5 are leaves; vertices 2 and 3 both root a path of two vertices.\n\n### Example 2\nInput:\n```\n1\n```\nOutput:\n```\n0\n```\n\n### Example 3\nInput:\n```\n5\n1 2\n1 3\n1 4\n4 5\n```\nOutput:\n```\n3\n```\nNote: The leaves 2, 3 and 5 form 3 pairs; vertex 4 has a child so it matches nothing.\n\nSolve this in Ruby, Java 17, JavaScript (Node.js), one complete program per language. Code only, no explanation.", "timestamp": 1794140403537}}
{"type": "message", "message": {"role": "assistant", "content": "### Ruby\n```ruby\ndata = STDIN.read.split.map(&:to_i)\nn = data[0]\nadj = Array.new(n + 1) { [] }\n(0...n - 1).each do |i|\n  a = data[1 + 2 * i]\n  b = data[2 + 2 * i]\n  adj[a] << b\n  adj[b] << a\nend\npar = Array.new(n + 1, 0)\norder = [1]\npar[1] = -1\ni = 0\nwhile i < order.size\n  v = order[i]\n  i += 1\n  adj[v].each do |w|\n    next if w == par[v]\n    par[w] = v\n    order << w\n  end\nend\nkids = Array.new(n + 1) { [] }\nid = Array.new(n + 1, 0)\ndict = {}\ncls = []\norder.reverse_each do |v|\n  key = kids[v].sort\n  c = dict[key]\n  if c.nil?\n    c = cls.size\n    dict[key] = c\n    cls << 0\n  end\n  cls[c] += 1\n  id[v] = c\n  kids[par[v]] << c if par[v] > 0\nend\nputs cls.sum { |c| c * (c - 1) / 2 }\n```\n\n### Java 17\n```java\nimport java.io.*;\nimport java.util.*;\n\npublic class Main {\n    public static void main(String[] args) throws IOException {\n        StreamTokenizer st = new StreamTokenizer(new BufferedInputStream(System.in));\n        st.nextToken();\n        int n = (int) st.nval;\n        int[] head = new int[n + 1], nxt = new int[2 * n], to = new int[2 * n];\n        Arrays.fill(head, -1);\n        int ec = 0;\n        for (int i = 0; i < n - 1; i++) {\n            st.nextToken(); int a = (int) st.nval;\n            st.nextToken(); int b = (int) st.nval;\n            to[ec] = b; nxt[ec] = head[a]; head[a] = ec++;\n            to[ec] = a; nxt[ec] = head[b]; head[b] = ec++;\n        }\n        int[] par = new int[n + 1], order = new int[n];\n        par[1] = -1;\n        order[0] = 1;\n        int sz = 1;\n        for (int i = 0; i < sz; i++) {\n            int v = order[i];\n            for (int e = head[v]; e >= 0; e = nxt[e]) {\n                int w = to[e];\n                if (w == par[v]) continue;\n                par[w] = v;\n                order[sz++] = w;\n            }\n        }\n        List<List<Integer>> kids = new ArrayList<>();\n        for (int i = 0; i <= n; i++) kids.add(new ArrayList<>());\n        HashMap<String, Integer> dict = new HashMap<>();\n        List<Long> cls = new ArrayList<>();\n        for (int i = n - 1; i >= 0; i--) {\n            int v = order[i];\n            List<Integer> k = kids.get(v);\n            Collections.sort(k);\n            StringBuilder sb = new StringBuilder();\n            for (int x : k) sb.append(x).append(',');\n            String key = sb.toString();\n            Integer c = dict.get(key);\n            if (c == null) {\n                c = cls.size();\n                dict.put(key, c);\n                cls.add(0L);\n            }\n            cls.set(c, cls.get(c) + 1);\n            if (par[v] > 0) kids.get(par[v]).add(c);\n        }\n        long ans = 0;\n        for (long c : cls) ans += c * (c - 1) / 2;\n        System.out.println(ans);\n    }\n}\n```\n\n### JavaScript (Node.js)\n```javascript\nconst t = require('fs').readFileSync(0, 'utf8').split(/\\s+/).filter(x => x).map(Number);\nconst n = t[0];\nconst adj = Array.from({ length: n + 1 }, () => []);\nfor (let i = 0; i < n - 1; i++) {\n  const a = t[1 + 2 * i], b = t[2 + 2 * i];\n  adj[a].push(b);\n  adj[b].push(a);\n}\nconst par = new Array(n + 1).fill(0);\npar[1] = -1;\nconst order = [1];\nfor (let i = 0; i < order.length; i++) {\n  const v = order[i];\n  for (const w of adj[v]) {\n    if (w === par[v]) continue;\n    par[w] = v;\n    order.push(w);\n  }\n}\nconst kids = Array.from({ length: n + 1 }, () => []);\nconst dict = new Map();\nconst cls = [];\nfor (let i = n - 1; i >= 0; i--) {\n  const v = order[i];\n  const k = kids[v].sort((x, y) => x - y);\n  const key = k.join(',');\n  let c = dict.get(key);\n  if (c === undefined) {\n    c = cls.length;\n    dict.set(key, c);\n    cls.push(0);\n  }\n  cls[c]++;\n  if (par[v] > 0) kids[par[v]].push(c);\n}\nlet ans = 0;\nfor (const c of cls) ans += c * (c - 1) / 2;\nconsole.log(String(ans));\n```", "timestamp": 1794140405511}}