Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdio>
- #include<algorithm>
- using namespace std;
- void MakeSet(int);
- int Find(int);
- bool Same_Component(int,int);
- void Union(int, int);
- int Components(int);
- struct Path {
- int origin;
- int destiny;
- int cost;
- }path[20005];
- bool operator < (Path a, Path b) {
- return a.cost < b.cost;
- }
- int root[1005];
- int rank[1005];
- int main() {
- int barns,connections;
- int mst = 0;
- scanf("%d %d",&barns,&connections);
- MakeSet(barns);
- for(int i=0;i<connections;i++){
- scanf("%d %d %d",&path[i].origin,&path[i].destiny,&path[i].cost);
- Union(path[i].origin,path[i].destiny);
- }
- if(Components(barns) != 1) printf("-1\n");
- else {
- sort(path,path+connections);
- MakeSet(barns+1);
- for(int i=connections-1;i>=0;i--) {
- if(!Same_Component(path[i].origin,path[i].destiny))
- mst += path[i].cost;
- Union(path[i].origin,path[i].destiny);
- }
- printf("%d\n",mst);
- }
- return 0;
- }
- void MakeSet(int n) {
- for(int i=0;i<n;i++) {
- root[i] = i;
- rank[i] = 0;
- }
- }
- int Find(int x) {
- if(x != root[x]) return root[x] = Find(root[x]);
- return x;
- }
- bool Same_Component(int x, int y) {
- if(Find(x) == Find(y)) return true;
- return false;
- }
- void Union(int x, int y) {
- int xroot = Find(x);
- int yroot = Find(y);
- if(rank[xroot] > rank[yroot]) root[yroot] = xroot;
- else {
- root[xroot] = yroot;
- if(rank[xroot] == rank[yroot]) rank[yroot]++;
- }
- }
- int Components(int n) {
- int nComponents = 0;
- for(int i=0;i<n;i++) {
- if(Find(i) == i) {
- root[nComponents] = i;
- nComponents++;
- }
- }
- return nComponents;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement