You are on page 1of 2

01/12/2016

#include
#include
#include
#include

UnionFind.html

<iostream>
<vector>
<map>
<set>

using namespace std;


class UF
{
int *id, cnt, *sz;
multiset<long int> m;
vector <multiset<long int>::iterator> v;
public:
UF(int N):v(N)
{
int k;
cnt = N;
id = new int[N];
sz = new int[N];
for(int i=0; i<N; i++)
{
id[i] = i;
sz[i] = 1;
cin >> k;
v[i] = m.insert(k);
}
}
~UF()
{
delete [] id;
delete [] sz;
}
int find(int p)
{
int root = p;
while (root != id[root])
root = id[root];
while (p != root)
{
int newp = id[p];
id[p] = root;
p = newp;
}
return root;
}
void merge(int x, int y)
{
int i = find(x);
int j = find(y);
if (i == j)
return;
long int new_val = *v[j] + *v[i];
m.erase(v[i]);
m.erase(v[j]);
if (sz[i] < sz[j])
{
id[i] = j;
sz[j] += sz[i];
}
else
{
le:///mnt/E/My%20Documents/Desktop/UnionFind.html

1/2

01/12/2016

UnionFind.html

id[j] = i;
sz[i] += sz[j];
}
v[i] = v[j] = m.insert(new_val);
cnt--;
}
bool connected(int x, int y)
{
return find(x) == find(y);
}
int count()
{
return cnt;
}
long int top() const
{
return *m.begin();
}
/*void print()
{
for (int i = 0; i < v.size(); i++)
cout << *v[i] << " ";
cout << "\n";
}*/
};
int main()
{
ios::sync_with_stdio(false);
int n, q, k, u, v;
cin >> n >> q;
UF uf(n);
for (int i = 0; i < q; i++)
{
cin >> u >> v;
uf.merge(u - 1, v - 1);
cout << uf.top() << "\n";
//uf.print();
}
return 0;
}

le:///mnt/E/My%20Documents/Desktop/UnionFind.html

2/2

You might also like