File tree Expand file tree Collapse file tree 1 file changed +104
-0
lines changed Expand file tree Collapse file tree 1 file changed +104
-0
lines changed Original file line number Diff line number Diff line change
1
+ // D-S-U -> disjoint set and union.....implementation
2
+
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ typedef long long int ll;
7
+ using ii= pair<ll,ll>;
8
+ #define F first
9
+ #define S second
10
+ #define MP make_pair
11
+ #define PB push_back
12
+ // using min_of_3=min({ll a,ll b,ll c});
13
+
14
+ ll parent[1001 ];
15
+ ll size[1001 ];
16
+ vector<ii> build; // roads to be built
17
+ vector<ii> demo; // roads to be demolished
18
+
19
+ void make_set (ll v)
20
+ {
21
+ parent[v]=v;
22
+ size[v]=1 ;
23
+ }
24
+
25
+ ll find_set (ll v) // In find_set(v) we actually find the representative or root of the subtree having node v..
26
+ { // As an optimization we use...COMPRESSION BY PATH ...where after finding a certain v...we set
27
+ if (parent[v]==v) // v's parent directly to its representative so as to shorten the path for future find_set calls...
28
+ {
29
+ return v;
30
+ }
31
+ else
32
+ {
33
+ return parent[v]=find_set (parent[v]); // be ware ...if you write parent[v]=find_set(parent[v])...you may get error/TLE
34
+ }
35
+ }
36
+
37
+
38
+ void union_set (ll u,ll v) // UNION OR MERGING 2 CONNECTED COMPONENTS TOGETHER...
39
+ {
40
+ u= find_set (u);
41
+ v= find_set (v);
42
+
43
+ if (u!=v)
44
+ {
45
+ if (size[u]<size[v]) // UNION BY SIZE OPTIMIZATION-> attach the tree with lower size to the tree with bigger size...
46
+ { // So that the size of tree may not grow much
47
+ swap (u,v);
48
+ }
49
+ parent[v]=u;
50
+ size[u]+=size[v];
51
+ }
52
+ }
53
+
54
+
55
+
56
+
57
+ int main ()
58
+ {
59
+ ios_base::sync_with_stdio (false );
60
+ cin.tie (NULL );cout.tie (NULL );
61
+
62
+ ll n;
63
+ cin>>n;
64
+ ll m=n-1 ;
65
+
66
+ for (ll i=1 ;i<=n;i++)
67
+ {
68
+ make_set (i);
69
+ }
70
+
71
+ while (m--)
72
+ {
73
+ ll a,b;
74
+ cin>>a>>b;
75
+
76
+ if (find_set (a)==find_set (b))
77
+ {
78
+ demo.PB ({a,b});
79
+ }
80
+ else
81
+ {
82
+ union_set (a,b);
83
+ }
84
+ }
85
+
86
+ for (ll i=2 ;i<=n;i++)
87
+ {
88
+ if (find_set (i)!=find_set (1 ))
89
+ {
90
+ build.PB ({i,1 });
91
+ union_set (i,1 );
92
+ }
93
+ }
94
+
95
+ ll x=build.size ();
96
+ cout<<build.size ()<<" \n " ;
97
+
98
+ for (ll i=0 ;i<x;i++)
99
+ {
100
+ cout<<demo[i].F <<" " <<demo[i].S <<" " <<build[i].F <<" " <<build[i].S <<" \n " ;
101
+ }
102
+
103
+
104
+ }
You can’t perform that action at this time.
0 commit comments