Created
October 20, 2016 16:56
-
-
Save tina1998612/b326406f5512a94b0e6ca3381cca4c5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//#include <bits/stdc++.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <cmath> | |
#include <cstdlib> | |
#include <set> | |
#include <sstream> | |
#include <vector> | |
#include <map> | |
#include <iostream> | |
#include <queue> | |
#include <algorithm> | |
#include <time.h> | |
#define PI 3.14159265 | |
#define N 100000+5 | |
#define ll long long | |
#define INF 2147483647 | |
using namespace std; | |
int n,m,p[N],has_cycle[N],x,y,ans,cnt; | |
struct E{ int x, y, c; } e[N]; | |
void init(){ for(int i=0;i<n;i++) p[i]=i, has_cycle[i]=0; ans=0; cnt=0;} | |
int findd(int x){ return (x==p[x])?x:findd(p[x]); } | |
void uni(int x,int y){ p[x]=y; } | |
bool cmp(E e1,E e2){ return e1.c>e2.c; } | |
int main(){ | |
while(scanf("%d%d",&n,&m) && n+m){ | |
init(); | |
for(int i=0;i<m;i++) { | |
scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].c); | |
} | |
sort(e,e+m,cmp); | |
for(int i=0;i<m;i++){ | |
x=findd(e[i].x); y=findd(e[i].y); | |
if(x!=y){ | |
if(has_cycle[x]&&has_cycle[y]) continue; | |
if(has_cycle[x]||has_cycle[y]) has_cycle[x]=1, has_cycle[y]=1; | |
uni(x,y); | |
ans+=e[i].c; | |
cnt++; | |
} | |
else{ | |
if(has_cycle[x]) continue; | |
has_cycle[x]=1; | |
ans+=e[i].c; | |
cnt++; | |
} | |
if(cnt==n) break; | |
} | |
printf("%d\n",ans); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment