-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoadConstruction.java
More file actions
94 lines (71 loc) · 2.03 KB
/
RoadConstruction.java
File metadata and controls
94 lines (71 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package DisJoint;
import java.util.ArrayList;
import java.util.Scanner;
public class RoadConstruction {
int parent[];
int size[];
int components, maxSize;
public static class Pair{
int compo , size;
public Pair(int compo , int size){
this.compo = compo;
this.size = size;
}
public int getFirst(){
return compo;
}
public int getSecond(){
return size;
}
}
public RoadConstruction(int n){
parent = new int[n+1];
size = new int[n+1];
for(int i = 0; i <= n; i++){
parent[i] = i;
size[i] = 1;
}
components = n;
maxSize = 1;
}
public int findParent(int node){
if(node == parent[node]){
return node;
}
return parent[node] = findParent(parent[node]);
}
public void union(int u , int v){
int u_p = findParent(u);
int v_p = findParent(v);
if(u_p == v_p){
return;
}
if(size[u_p] < size[v_p]){
parent[u_p] = v_p;
size[v_p] += size[u_p];
maxSize = Math.max(maxSize, size[v_p]);
}else{
parent[v_p] = u_p;
size[u_p] += size[v_p];
maxSize = Math.max(maxSize, size[u_p]);
}
components--;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Pair> ans = new ArrayList<>();
int n = sc.nextInt();
RoadConstruction rc = new RoadConstruction(n);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
int u = sc.nextInt();
int v = sc.nextInt();
rc.union(u, v);
// System.out.println(rc.components + " " + rc.maxSize);
ans.add(new Pair(rc.components, rc.maxSize));
}
for (Pair result : ans) {
System.out.println(result.getFirst() + " " + result.getSecond());
}
}
}