1249 B2. Books Exchange (hard version)
16 March 2025
[ algorithms , codeforces , dsu ]

Give this problem a try 1249 B2. Books Exchange (hard version).


Approach


Example Code

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

public class Solution {
	static class DSU {
		int[] parent;
		int[] sz;

		public DSU(int N) {
			parent = new int[N];
			sz = new int[N];
			for (int i = 0; i < N; i++) {
				parent[i] = i;
				sz[i] = 1;
			}
		}

		public int find(int v) {
			if (parent[v] == v) return parent[v];
			return parent[v] = find(parent[v]); // path compression
		}

		public void union(int a, int b) {
			a = find(a);
			b = find(b);
			if (a != b) {
				if (sz[a] <= sz[b]) {
					int tmp = a;
					a = b;
					b = tmp;
				}
				parent[b] = a;
				sz[a] += sz[b];
			}
		}

		public int query(int v) {
			return sz[v];
		}
	}

    public static void main(String[] args) throws Exception {
        // FastScanner io = new FastScanner("");
		FastScanner io = new FastScanner();

		int q = io.nextInt();
		for (int i = 0; i < q; i++) {
			int n = io.nextInt();
			DSU dsu = new DSU(n);
			for (int j = 0; j < n; j++) {
				int p = io.nextInt()-1;
				dsu.union(j, p);
			}
			for (int j = 0; j < n; j++) {
				int p = dsu.find(j);
				int a = dsu.query(p);
				if (j < n-1) io.print(a + " ");
				else io.println(a);
			}
		}

		io.close();
    }

    /**
        RESERVED NUMBERS
    */
    public static int MOD = 1_000_000_007; // prime number
	public static int INF = 1_000_000_007; // infinity number

    /**
        DATA STRUCTURES
    */
    static class MultiSet {
        static TreeMap<Integer, Integer> multiset;
		public MultiSet() { multiset = new TreeMap<>(); }
        static void add(int x) {
            multiset.putIfAbsent(x, 0);
            multiset.put(x, multiset.get(x)+1);
        }
        static void remove(int x) {
            multiset.putIfAbsent(x, 0);
            multiset.put(x, multiset.get(x)-1);
            if (multiset.get(x) <= 0) multiset.remove(x);
        }
    }

    /**
        IO
    */
    static class FastScanner extends PrintWriter {
        private BufferedReader br;
        private StringTokenizer st;
		
		// standard input
        public FastScanner() { this(System.in, System.out); }
		public FastScanner(InputStream i, OutputStream o) {
            super(o);
			st = new StringTokenizer("");
            br = new BufferedReader(new InputStreamReader(i));
        }
		// USACO-style file input
        public FastScanner(String problemName) throws IOException {
            super(problemName + ".out");
			st = new StringTokenizer("");
            br = new BufferedReader(new FileReader(problemName + ".in"));
        }

        // returns null if no more input
        public String next() {
            try {
                while (st == null || !st.hasMoreTokens())
                    st = new StringTokenizer(br.readLine());
                return st.nextToken();
            } catch (Exception e) { }
            return null;
        }
        public int nextInt() { return Integer.parseInt(next()); }  
        public double nextDouble() { return Double.parseDouble(next()); }   
        public long nextLong() { return Long.parseLong(next()); }   
    }
}

Complexity Analysis

  • Time Complexity: $O(Q\times N \times \alpha(N))$
    • Where $\alpha(N)$ is the inverse Ackermann function, which grows very slowly. $\alpha(N) \leq 4$ for $N < 10^{600}$
    • Worst case scenario of DSU would be $O(logN)$
  • Space Complexity: $O(N)$

Sign-off

Congratulations on making it this far! Best of luck in your future competitions!