Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 11987 - Almost Union-Find
Source : UVA Online Judge
Category : Data Structure
Algorithm : Disjoint Set Union
Verdict : Accepted
- #include <bits/stdc++.h>
-
- using namespace std;
-
- static const int maxn = 3e5 + 5;
-
- struct node
- {
- int ele, sum, father, ffather;
- node(int ele = 0, int sum = 0, int father = 0, int ffather) :
- ele(ele), sum(sum), father(father), ffather(ffather) {}
- } ff[maxn];
-
- void makeSet(int n)
- {
- for (int i = 1; i <= n; i++)
- {
- ff[i].ele = ff[n+i].ele = 1;
- ff[i].sum = ff[n+i].sum = i;
- ff[i].father = ff[n+i].father = n+i;
- }
- }
-
- int findRep(int r)
- {
- if (ff[r].father == r) return ff[r].father;
- return ff[r].father = findRep(ff[r].father);
- }
-
- void Union(int u, int v)
- {
- int p = findRep(u);
- int q = findRep(v);
- if (p == q) return;
- ff[q].ele += ff[p].ele; ff[p].ele = 0;
- ff[q].sum += ff[p].sum; ff[p].sum = 0;
- ff[p].father = q;
- }
-
- void Move(int u, int v)
- {
- int p = findRep(u);
- int q = findRep(v);
- if (p == q) return;
- ff[q].ele += 1;
- ff[q].sum += u;
- ff[p].ele -= 1;
- ff[p].sum -= u;
- ff[u].father = q;
- }
-
- void Res(int u)
- {
- int p = findRep(u);
- printf("%d %d\n", ff[p].ele, ff[p].sum);
- }
-
- int main()
- {
-
-
- int n, q;
- while (scanf("%d %d", &n, &q) == 2)
- {
- makeSet(n);
- while (q--)
- {
- int type;
- scanf("%d", &type);
- if (type == 1)
- {
- int u, v;
- scanf("%d %d", &u, &v);
- Union(u, v);
- }
- else if (type == 2)
- {
- int u, v;
- scanf("%d %d", &u, &v);
- Move(u, v);
- }
- else if (type == 3)
- {
- int u;
- scanf("%d", &u);
- Res(u);
- }
- }
- }
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.