hdu 3367 Pseudoforest

http://acm.hdu.edu.cn/showproblem.php?pid=3367

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define maxn 20000
 5 using namespace std;
 6 
 7 int n,m;
 8 int f[maxn],cicl[maxn];
 9 struct node
10 {
11     int u,v,w;
12     bool operator <(const node &a) const
13     {
14         return w>a.w;
15     }
16 }p[maxn*5];
17 int find1(int x)
18 {
19     if(x==f[x]) return x;
20     return f[x]=find1(f[x]);
21 }
22 
23 int kruskal()
24 {
25     int ans=0;
26     memset(cicl,0,sizeof(cicl));
27     for(int i=0; i<=n; i++) f[i]=i;
28     for(int i=0; i<m; i++)
29     {
30         int fx=find1(p[i].u);
31         int fy=find1(p[i].v);
32         if(fx==fy)
33         {
34             if(!cicl[fx])
35             {
36                 cicl[fx]=1;
37                 ans+=p[i].w;
38             }
39             continue;
40         }
41         if(cicl[fx]&&cicl[fy]) continue;
42         if(cicl[fx]) f[fy]=fx;
43         else f[fx]=fy;
44         ans+=p[i].w;
45     }
46     return ans;
47 }
48 
49 int main()
50 {
51     while(scanf("%d%d",&n,&m)!=EOF)
52     {
53         if(n==0&&m==0) break;
54         for(int i=0; i<m; i++)
55         {
56             scanf("%d%d%d",&p[i].u,&p[i].v,&p[i].w);
57         }
58         sort(p,p+m);
59         printf("%d\n",kruskal());
60     }
61     return 0;
62 }
View Code

 

posted @ 2014-05-26 21:18  null1019  阅读(155)  评论(0编辑  收藏  举报