{ }codelper
equality and coerciongraphs (adjacency lists)P0413

Comparing lists that contain themselves

Memory holds n values, numbered 1 to n.
Each value is an integer or a list.
A list holds zero or more value numbers, in order.
A list may hold itself, or hold a list that holds it back.
So writing a list out in full can go on forever.
Two values are compared by the following rule.
A "path" is a sequence of zero or more positions, each at least 1.
Following a path from a value x means: for each position p in the path, move to the value held p-th (counting from 1) by the list you are at.
If along the way you reach an integer, or a list holding fewer than p values, the path cannot be followed from x.
For a path that can be followed to the end from both x and y, call the two values reached u and v.
For the empty path, u is x and v is y.
x and y are different if some such path gives u and v that are one of these three: one is an integer and the other is a list; both are integers with different values; both are lists holding different numbers of values.
If there is no such path, x and y are equal.
So two values with the same number are always equal, and a list holding only itself and two lists holding each other once are all equal to one another.
The first line gives n and q separated by a single space.
The next n lines give the values from number 1 in order: an integer as "num v", a list as "list k c1 … ck".
k is how many values it holds, and c1 to ck are the numbers of the held values in order.
Then q lines each give a query "a b".
For each query print "yes" on its own line if value a and value b are equal, and "no" if they are different.
The built-in equality of each language (==, equals) either never ends on a cycle or only asks whether it is the same list, so write a comparison function that survives cycles yourself.
Grading looks only at the output.

Input
1 ≤ n ≤ 1,000, 1 ≤ q ≤ 50, 0 ≤ v ≤ 10⁹, 0 ≤ k, sum of k over all lists ≤ 2,500, 1 ≤ cᵢ ≤ n, 1 ≤ a, b ≤ n.
a and b may be equal.
Output
q lines: "yes" or "no" for each query
Example 1 · stdin
9 5
num 7
list 2 1 2
list 2 1 4
list 2 1 3
list 2 6 5
num 7
list 2 1 8
list 2 1 9
num 8
2 3
2 5
2 7
1 6
1 2
stdout
yes
yes
no
yes
no
Example 2 · stdin
4 4
list 1 1
list 1 3
list 1 2
list 0
1 2
2 3
1 4
4 4
stdout
yes
yes
no
yes
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

All 8 languages are accepted.
The point is that in every language the built-in equality cannot solve this.
In example 1, value 2 is the Python list a = [7]; a.append(a), and values 3 and 4 are two [7, …] lists holding each other.
Trap one: building real lists and leaving it to the language's equality.
Python == compares lists element by element with == again, so values[2] == values[3] digs forever and stops with RecursionError (a == a is True at once because the elements are the same object by is).
Java ArrayList.equals also calls equals on each element and throws StackOverflowError.
C# List<object>.Equals, JavaScript/TypeScript === and Craykon list == only ask whether it is the same list (reference), so they answer no to 2 3.
C has no list comparison, and C++ std::vector == compares elements by value, but since values are stored as numbers it only compares numbers.
Trap two: turning "same shape and equal at every position" directly into recursion never ends on a cycle (JavaScript: RangeError: Maximum call stack size exceeded).
Trap three: to break cycles, saying "different" when you meet a pair already on the current path gets cycles that are equal wrong, such as 2 3 and 2 5 in example 1.
A difference always shows up along a finite path, so a pair met again must be "assumed equal" and skipped.
The reference solution groups values assumed equal with union-find.
It takes one stacked pair, finds the representatives of both groups, skips if they are the same, and otherwise compares the representatives' surface (an integer's value, a list's length), merges them and stacks their held values pairwise.
A representative that has been merged never becomes a representative again, so one query stacks at most (sum of all k) + 1 pairs.
Trap four: assumptions made in a query that ended in no may be wrong.
If the groups are not restarted for each query, asking about [1, 1] and [1, 2] twice gives no the first time and yes the second.

Pythonmain.py · 57 lines
import sys  def main():    data = sys.stdin.read().split()    n, q = int(data[0]), int(data[1])    pos = 2    is_list = [False] * (n + 1)    num = [0] * (n + 1)    items = [[] for _ in range(n + 1)]    for i in range(1, n + 1):        if data[pos] == "num":            num[i] = int(data[pos + 1])            pos += 2        else:            k = int(data[pos + 1])            is_list[i] = True            items[i] = [int(c) for c in data[pos + 2 : pos + 2 + k]]            pos += 2 + k     def same(a, b):        # 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다        parent = list(range(n + 1))         def find(x):            while parent[x] != x:                parent[x] = parent[parent[x]]                x = parent[x]            return x         todo = [(a, b)]        while todo:            u, v = todo.pop()            # 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다            x, y = find(u), find(v)            if x == y:                continue  # 이미 같다고 가정한 짝: 다시 볼 필요가 없다(고리도 여기서 끝난다)            if is_list[x] != is_list[y]:                return False            if not is_list[x]:                if num[x] != num[y]:                    return False            elif len(items[x]) != len(items[y]):                return False            parent[x] = y            todo.extend(zip(items[x], items[y]))        return True     out = []    for _ in range(q):        a, b = int(data[pos]), int(data[pos + 1])        pos += 2        out.append("yes" if same(a, b) else "no")    print("\n".join(out))  main()
JavaScriptmain.js · 50 lines
const data = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);let pos = 0;const n = Number(data[pos++]);const q = Number(data[pos++]);const isList = new Array(n + 1).fill(false);const num = new Array(n + 1).fill(0);const items = Array.from({ length: n + 1 }, () => []);for (let i = 1; i <= n; i++) {  if (data[pos++] === "num") {    num[i] = Number(data[pos++]);  } else {    const k = Number(data[pos++]);    isList[i] = true;    for (let j = 0; j < k; j++) items[i].push(Number(data[pos++]));  }} // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다function same(a, b) {  const parent = Array.from({ length: n + 1 }, (_, i) => i);  const find = (x) => {    while (parent[x] !== x) {      parent[x] = parent[parent[x]];      x = parent[x];    }    return x;  };  const todo = [[a, b]];  while (todo.length > 0) {    const [u, v] = todo.pop();    // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다    const x = find(u);    const y = find(v);    if (x === y) continue; // 이미 같다고 가정한 짝(고리도 여기서 끝난다)    if (isList[x] !== isList[y]) return false;    if (!isList[x] && num[x] !== num[y]) return false;    if (items[x].length !== items[y].length) return false;    parent[x] = y;    for (let t = 0; t < items[x].length; t++) todo.push([items[x][t], items[y][t]]);  }  return true;} const out = [];for (let i = 0; i < q; i++) {  const a = Number(data[pos++]);  const b = Number(data[pos++]);  out.push(same(a, b) ? "yes" : "no");}console.log(out.join("\n"));
TypeScriptmain.ts · 62 lines
import { readFileSync } from "node:fs"; // 값은 수이거나, 다른 값의 번호를 담은 목록이다type Value = { kind: "num"; v: number } | { kind: "list"; items: number[] }; const data: string[] = readFileSync(0, "utf8").trim().split(/\s+/);let pos = 0;const n = Number(data[pos++]);const q = Number(data[pos++]);const values: Value[] = [{ kind: "list", items: [] }]; // 0번은 쓰지 않는다for (let i = 1; i <= n; i++) {  if (data[pos++] === "num") {    values.push({ kind: "num", v: Number(data[pos++]) });  } else {    const k = Number(data[pos++]);    const items: number[] = [];    for (let j = 0; j < k; j++) items.push(Number(data[pos++]));    values.push({ kind: "list", items });  }} // 두 값이 겉보기에(수의 값, 목록의 길이) 같은지만 본다function sameSurface(x: Value, y: Value): boolean {  if (x.kind === "num") return y.kind === "num" && x.v === y.v;  return y.kind === "list" && x.items.length === y.items.length;} // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다function same(a: number, b: number): boolean {  const parent: number[] = Array.from({ length: n + 1 }, (_, i) => i);  const find = (x: number): number => {    while (parent[x] !== x) {      parent[x] = parent[parent[x]];      x = parent[x];    }    return x;  };  const todo: [number, number][] = [[a, b]];  while (todo.length > 0) {    const [u, v] = todo.pop()!;    // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다    const x = find(u);    const y = find(v);    if (x === y) continue; // 이미 같다고 가정한 짝(고리도 여기서 끝난다)    const vx = values[x];    const vy = values[y];    if (!sameSurface(vx, vy)) return false;    parent[x] = y;    if (vx.kind === "list" && vy.kind === "list") {      vx.items.forEach((c, t) => todo.push([c, vy.items[t]]));    }  }  return true;} const out: string[] = [];for (let i = 0; i < q; i++) {  const a = Number(data[pos++]);  const b = Number(data[pos++]);  out.push(same(a, b) ? "yes" : "no");}console.log(out.join("\n"));
JavaMain.java · 74 lines
import java.io.*;import java.util.*; public class Main {    static int n;    static boolean[] isList;    static long[] num;    static int[][] items;    static int[] parent;     static int find(int x) {        while (parent[x] != x) {            parent[x] = parent[parent[x]];            x = parent[x];        }        return x;    }     // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다    static boolean same(int a, int b) {        for (int v = 0; v <= n; v++) parent[v] = v;        ArrayDeque<int[]> todo = new ArrayDeque<>();        todo.push(new int[] {a, b});        while (!todo.isEmpty()) {            int[] pr = todo.pop();            // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다            int x = find(pr[0]), y = find(pr[1]);            if (x == y) continue; // 이미 같다고 가정한 짝(고리도 여기서 끝난다)            if (isList[x] != isList[y]) return false;            if (!isList[x] && num[x] != num[y]) return false;            if (items[x].length != items[y].length) return false;            parent[x] = y;            for (int t = 0; t < items[x].length; t++) todo.push(new int[] {items[x][t], items[y][t]});        }        return true;    }     public static void main(String[] args) throws IOException {        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));        in.nextToken();        n = (int) in.nval;        in.nextToken();        int q = (int) in.nval;        isList = new boolean[n + 1];        num = new long[n + 1];        items = new int[n + 1][0];        parent = new int[n + 1];        for (int i = 1; i <= n; i++) {            in.nextToken();            String kind = in.sval;            in.nextToken();            if (kind.equals("num")) { // 문자열은 ==가 아니라 equals로 비교한다                num[i] = (long) in.nval;            } else {                isList[i] = true;                int k = (int) in.nval;                items[i] = new int[k];                for (int j = 0; j < k; j++) {                    in.nextToken();                    items[i][j] = (int) in.nval;                }            }        }        StringBuilder sb = new StringBuilder();        for (int i = 0; i < q; i++) {            in.nextToken();            int a = (int) in.nval;            in.nextToken();            int b = (int) in.nval;            sb.append(same(a, b) ? "yes" : "no").append('\n');        }        System.out.print(sb);    }}
C#Main.cs · 79 lines
using System;using System.Collections.Generic;using System.IO;using System.Text; class Program{    static int n;    static bool[] isList;    static long[] num;    static int[][] items;    static int[] parent;     static int Find(int x)    {        while (parent[x] != x)        {            parent[x] = parent[parent[x]];            x = parent[x];        }        return x;    }     // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다    static bool Same(int a, int b)    {        for (int v = 0; v <= n; v++) parent[v] = v;        var todo = new Stack<(int, int)>();        todo.Push((a, b));        while (todo.Count > 0)        {            var (u, v) = todo.Pop();            // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다            int x = Find(u), y = Find(v);            if (x == y) continue; // 이미 같다고 가정한 짝(고리도 여기서 끝난다)            if (isList[x] != isList[y]) return false;            if (!isList[x] && num[x] != num[y]) return false;            if (items[x].Length != items[y].Length) return false;            parent[x] = y;            for (int t = 0; t < items[x].Length; t++) todo.Push((items[x][t], items[y][t]));        }        return true;    }     static void Main()    {        string[] data = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);        int pos = 0;        n = int.Parse(data[pos++]);        int q = int.Parse(data[pos++]);        isList = new bool[n + 1];        num = new long[n + 1];        items = new int[n + 1][];        parent = new int[n + 1];        for (int i = 0; i <= n; i++) items[i] = Array.Empty<int>();        for (int i = 1; i <= n; i++)        {            if (data[pos++] == "num") // C#의 string ==는 내용을 비교한다            {                num[i] = long.Parse(data[pos++]);            }            else            {                isList[i] = true;                int k = int.Parse(data[pos++]);                items[i] = new int[k];                for (int j = 0; j < k; j++) items[i][j] = int.Parse(data[pos++]);            }        }        var sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            int a = int.Parse(data[pos++]);            int b = int.Parse(data[pos++]);            sb.Append(Same(a, b) ? "yes" : "no").Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 67 lines
#include <iostream>#include <numeric>#include <string>#include <utility>#include <vector> struct Value {    bool isList = false;    long long num = 0;    std::vector<int> items; // 담은 값의 번호}; int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int n, q;    std::cin >> n >> q;    std::vector<Value> values(n + 1);    for (int i = 1; i <= n; i++) {        std::string kind;        std::cin >> kind;        if (kind == "num") {            std::cin >> values[i].num;        } else {            int k;            std::cin >> k;            values[i].isList = true;            values[i].items.resize(k);            for (int& c : values[i].items) std::cin >> c;        }    }     // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다    std::vector<int> parent(n + 1);    auto find = [&](int x) {        while (parent[x] != x) {            parent[x] = parent[parent[x]];            x = parent[x];        }        return x;    };    auto same = [&](int a, int b) {        std::iota(parent.begin(), parent.end(), 0);        std::vector<std::pair<int, int>> todo{{a, b}};        while (!todo.empty()) {            auto [u, v] = todo.back();            todo.pop_back();            // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다            int x = find(u), y = find(v);            if (x == y) continue; // 이미 같다고 가정한 짝(고리도 여기서 끝난다)            const Value& vx = values[x];            const Value& vy = values[y];            if (vx.isList != vy.isList) return false;            if (!vx.isList && vx.num != vy.num) return false;            if (vx.items.size() != vy.items.size()) return false;            parent[x] = y;            for (size_t t = 0; t < vx.items.size(); t++) todo.emplace_back(vx.items[t], vy.items[t]);        }        return true;    };     for (int i = 0; i < q; i++) {        int a, b;        std::cin >> a >> b;        std::cout << (same(a, b) ? "yes" : "no") << '\n';    }}
Cmain.c · 71 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> #define MAXN 1000#define MAXK 2500 static int n;static int isList[MAXN + 1];static long num[MAXN + 1];static int start[MAXN + 1], len[MAXN + 1]; /* i번 목록이 담은 번호: kids[start[i]] .. kids[start[i] + len[i] - 1] */static int kids[MAXK];static int parent[MAXN + 1];static int sx[MAXK + 1], sy[MAXK + 1]; /* 아직 볼 짝 */ static int find(int x) {    while (parent[x] != x) {        parent[x] = parent[parent[x]];        x = parent[x];    }    return x;} /* 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). 질문마다 새로 시작한다 */static int same(int a, int b) {    for (int v = 0; v <= n; v++) parent[v] = v;    int top = 0;    sx[top] = a;    sy[top] = b;    top++;    while (top > 0) {        top--;        /* 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다 */        int x = find(sx[top]), y = find(sy[top]);        if (x == y) continue; /* 이미 같다고 가정한 짝(고리도 여기서 끝난다) */        if (isList[x] != isList[y]) return 0;        if (!isList[x] && num[x] != num[y]) return 0;        if (len[x] != len[y]) return 0;        parent[x] = y;        for (int t = 0; t < len[x]; t++) {            sx[top] = kids[start[x] + t];            sy[top] = kids[start[y] + t];            top++;        }    }    return 1;} int main(void) {    int q;    if (scanf("%d %d", &n, &q) != 2) return 0;    int used = 0;    char kind[8];    for (int i = 1; i <= n; i++) {        scanf("%7s", kind);        if (strcmp(kind, "num") == 0) { /* 문자열은 ==가 아니라 strcmp로 비교한다 */            scanf("%ld", &num[i]);        } else {            isList[i] = 1;            scanf("%d", &len[i]);            start[i] = used;            for (int j = 0; j < len[i]; j++) scanf("%d", &kids[used++]);        }    }    for (int i = 0; i < q; i++) {        int a, b;        scanf("%d %d", &a, &b);        puts(same(a, b) ? "yes" : "no");    }    return 0;}
Craykonmain.cray · 91 lines
첫줄 = Console.ReadNumbers();n = 첫줄[0];q = 첫줄[1];isList = NewList(n + 1, false);num = NewList(n + 1, 0);items = [[]]; // items[i] = i번 목록이 담은 값의 번호들(0번은 쓰지 않는다)for (i = 1; i <= n; i++){    p = Console.ReadLine().Trim().Split(" ");    kids = [];    if (p[0] == "num")    {        num[i] = p[1].ToNumber();    }    else    {        isList[i] = true;        for (j = 2; j < p.Count; j++)        {            kids.Add(p[j].ToNumber());        }    }    items.Add(kids);} // 같다고 '가정한' 값들을 한 묶음으로 둔다(합치기-찾기). parent는 질문마다 새로 채운다parent = NewList(n + 1, 0); 찾기(x){    while (parent[x] != x)    {        parent[x] = parent[parent[x]];        x = parent[x];    }    return x;} // 목록끼리 ==는 같은 목록인지만 물으니, 담은 것을 짝지어 따라가며 직접 비교한다같은가(a, b){    for (v = 0; v <= n; v++)    {        parent[v] = v;    }    xs = [a]; // 아직 볼 짝: xs[t]와 ys[t]    ys = [b];    while (xs.Count > 0)    {        // 묶음의 대표끼리 비교한다. 대표는 한 번 합쳐지면 다시 대표가 되지 않으니, 짝은 담은 수의 합만큼만 쌓인다        x = 찾기(xs[xs.Count - 1]);        y = 찾기(ys[ys.Count - 1]);        xs.RemoveAt(xs.Count - 1);        ys.RemoveAt(ys.Count - 1);        if (x != y)        {            if (isList[x] != isList[y])            {                return false;            }            if (!isList[x] && num[x] != num[y])            {                return false;            }            if (items[x].Count != items[y].Count)            {                return false;            }            parent[x] = y; // 같다고 가정한다: 고리를 돌아 이 짝을 다시 만나면 위에서 건너뛴다            for (t = 0; t < items[x].Count; t++)            {                xs.Add(items[x][t]);                ys.Add(items[y][t]);            }        }    }    return true;} for (i = 0; i < q; i++){    ab = Console.ReadNumbers();    if (같은가(ab[0], ab[1]))    {        Console.WriteLine("yes");    }    else    {        Console.WriteLine("no");    }}