-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathDisjointSetUnion.java
More file actions
118 lines (83 loc) · 1.42 KB
/
DisjointSetUnion.java
File metadata and controls
118 lines (83 loc) · 1.42 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class GFG
{
static int N = 100010;
static class Edge
{
int u, v;
public Edge(int u, int v)
{
this.u = u;
this.v = v;
}
}
static int []id = new int[N];
static int []sz = new int[N];
static int Root(int idx)
{
int i = idx;
while(i != id[i])
{
id[i] = id[id[i]];
i = id[i];
}
return i;
}
static void Union(int a, int b)
{
int i = Root(a), j = Root(b);
if (i != j)
{
if(sz[i] >= sz[j])
{
id[j] = i;
sz[i] += sz[j];
sz[j] = 0;
}
else
{
id[i] = j;
sz[j] += sz[i];
sz[i] = 0;
}
}
}
static void UnionUtil(Edge e[], int W[], int q)
{
for(int i = 0; i < q; i++)
{
int u, v;
u = e[i].u;
v = e[i].v;
u--;
v--;
if(W[u] % 2 == 0 && W[v] % 2 == 0)
Union(u, v);
}
}
static int findMax(int n, int W[])
{
int maxi = 0;
for(int i = 1; i < n; i++)
if(W[i] % 2 == 0)
maxi = Math.max(maxi, sz[i]);
return maxi;
}
public static void main(String[] args)
{
int W[] = {1, 2, 6, 4, 2, 0, 3};
int n = W.length;
for(int i = 0; i < n; i++)
{
id[i] = i;
sz[i] = 1;
}
Edge e[] = {new Edge(1, 2), new Edge(1, 3),
new Edge(2, 4), new Edge(2, 5),
new Edge(4, 6), new Edge(6, 7)};
int q = e.length;
UnionUtil(e, W, q);
int maxi = findMax(n, W);
System.out.printf("Maximum size of the subtree with ");
System.out.printf("even weighted nodes = %d\n", maxi);
}
}