Advertisement
Guest User

426

a guest
May 24th, 2015
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. import java.io.*;
  2.  
  3. public class Solution {
  4.  
  5.     private static int[] rab;
  6.     private static int[] l;
  7.  
  8.     private static Pair up (int a) {
  9.         if (rab[a] == a) {
  10.             return new Pair(a, 0);
  11.         }
  12.         Pair p = up (rab[a]);
  13.         p.y += l[a];
  14.         l[a] = p.y;
  15.         rab[a] = p.x;
  16.         return p;
  17.     }
  18.  
  19.     public static void main(String[] args) throws IOException {
  20.         BufferedReader in = new BufferedReader(new FileReader("input.txt"));
  21.         String[] arr = in.readLine().split(" ");
  22.  
  23.         int n = Integer.parseInt(arr[0]);
  24.         int m = Integer.parseInt(arr[1]);
  25.  
  26.         rab = new int[n];
  27.         l = new int[n];
  28.  
  29.         for (int i = 0; i < n; i++) {
  30.             rab[i] = i;
  31.         }
  32.  
  33.         PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
  34.  
  35.         for (int i = 0; i < m; i++) {
  36.             arr = in.readLine().split(" ");
  37.             int z = Integer.parseInt(arr[0]);
  38.             if (z == 1) {
  39.                 int a = Integer.parseInt(arr[1]) - 1;
  40.                 int b = Integer.parseInt(arr[2]) - 1;
  41.                 rab[a] = b;
  42.                 l[a] = 1;
  43.             } else {
  44.                 int c = Integer.parseInt(arr[1]) - 1;
  45.                 Pair d = up(c);
  46.                 writer.println(d.y);
  47.             }
  48.         }
  49.  
  50.         writer.close();
  51.     }
  52.  
  53.     private static final class Pair {
  54.         private int x;
  55.         private int y;
  56.  
  57.         private Pair(int x, int y) {
  58.             this.x = x;
  59.             this.y = y;
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement