Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class UnionFind {
- static Scanner scan = new Scanner(System.in);
- final static int maxnodos = (int) (1e6+1);
- static int[] altura = new int[maxnodos+1];
- static int[] padre = new int[maxnodos+1];
- static void init()
- {
- for(int i = 1; i <= maxnodos; i++)
- {
- altura[i] = 1;
- padre[i] = i;
- }
- }
- static int find(int a)
- {
- int retValue = padre[a];
- if(padre[a] != a)
- {
- retValue = find(padre[a]);
- }
- padre[a] = retValue;
- return retValue;
- }
- static boolean check(int a , int b)
- {
- return find(a) == find(b);
- }
- static void union(int a, int b)
- {
- a = find(a);
- b = find(b);
- if(a == b) return;
- if(altura[b]> altura[a])
- {
- int t = b;
- b = a;
- a = t;
- }
- padre[b]= a;
- altura[a]+= altura[b];
- }
- public static void main(String[] args) {
- char x;
- int a, b;
- init();
- while((x= scan.next().charAt(0)) != 'F')
- {
- a = scan.nextInt();
- b = scan.nextInt();
- if(x == 'P') System.out.println(check(a, b) ? "S" : "N");
- else union(a, b);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment