hdu 3367 Pseudoforest
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3367
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<vector> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn = 10005; 9 const int maxm = 100050; 10 11 struct Edge{ 12 int u,v,c; 13 bool operator < (const Edge & rh) const{ 14 return c > rh.c; 15 } 16 }; 17 vector<Edge> e; 18 int p[maxn]; 19 int n,m; 20 bool flag[maxn]; 21 22 int find(int x){ 23 return x == p[x] ? x : p[x] = find(p[x]); 24 } 25 26 27 int main() 28 { 29 //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} 30 31 while(cin>>n>>m && (n || m)){ //这儿也有点问题啊 32 e.clear(); 33 for(int i=1;i<=m;i++){ 34 int u,v,c; 35 scanf("%d%d%d",&u,&v,&c); 36 e.push_back((Edge){u,v,c}); 37 } 38 sort(e.begin(),e.end()); 39 for(int i=0;i<n;i++) p[i] = i; 40 memset(flag,0,sizeof(flag)); 41 long long ans = 0; 42 for(int i=0;i<m;i++){ 43 int a = find(e[i].u),b = find(e[i].v); 44 //printf("%d %d %d %d \n",e[i].u,e[i].v,a,b); 45 if(a != b && (!flag[a] || !flag[b])){ 46 //这儿出现问题,没考虑到a所在的树与b所在的树不在同一个树上,但是两个数都有一个环 47 if(flag[a]) p[b] = a; //这儿出问题了; 48 else p[a] = b; 49 50 ans += e[i].c; 51 } 52 else if(a == b && !flag[a]){ 53 ans += e[i].c; 54 flag[a] = true; 55 } 56 // printf("%d\n",ans); 57 } 58 cout<<ans<<endl; 59 } 60 }