我们一起学猫叫 一起喵喵喵喵喵(并查集判环)

我们一起学猫叫 一起喵喵喵喵喵

Description

我们一起学猫叫

一起喵喵喵喵喵

在你面前撒个娇

哎呦喵喵喵喵喵

我的心脏砰砰跳

迷恋上你的坏笑

你不说爱我我就喵喵喵

《西虹市首富》的故事发生在《夏洛特烦恼》中的特烦恼之城西虹市。

混迹于丙级业余足球队的守门员王多鱼(沈腾饰),因比赛失利被开除离队。

正处于人生最低谷的他接受了神秘台湾财团一个月花光十亿资金的挑战,。

于是王多鱼举办了一个比赛,比赛为一道题目,解决出的人将获得1000万的奖励

题目为:

王多鱼定义了一个喵喵树,(喵喵树的概念:一个无向图,图中任意两点可达,且喵喵树上最多有一个环)

喵喵树的价值为喵喵树上所有边权之和。

王多鱼要求图中所有喵喵树(一个图上可以有多个喵喵树)价值之和最大,你能告诉他结果吗,来获取1000万吗?

Input

输入:

多组输入

第一行,n个点,m条边 接下来m行,每行三个数,分别代表起点,终点,边权

n(0 < n <= 10000)

m(0 <= m <= 100000)

保证最后结果在int范围内

当n等于0,m等于0读入结束

Output

输出:题意中的结果

 Sample Input 1

3 3
0 1 1
1 2 1
2 0 1

Sample Output 1

3
Sample Input 2 

4 5
0 1 1
1 2 1
2 3 1
3 0 1
0 2 2

Sample Output 2

5

Sample Input 3 

6 7
0 1 9
0 2 6
1 2 8
3 4 5
4 5 5
3 5 4
2 4 1

Sample Output 3

37

HInt

样例3:

6 7

0 1 9

0 2 6

1 2 8

3 4 5

4 5 5

3 5 4

2 4 1

正确的方法答案是37,

选择(0,1),(1,2),(0,2),(3,4),(3,5),(4,5)

要求是每个喵喵树中最多只能有一个环!

题解:保证有一个环

1>如果是两棵树在进行合并,如果两棵树都有环,则不能进行合并,如果只有一棵树有环,可以进行合并。

2>如果是同一棵树在进行合并,那么同一棵树上要合并的这两个节点必定没有环。

vis数组用来标记是否有环的存在。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn=1e5+10;
 7 struct node{
 8     int l;
 9     int r;
10     int val;
11 }e[maxn];
12 int ans,n,m;
13 int f[maxn],vis[maxn];
14 int getf(int x)
15 {
16     return f[x]==x?x:f[x]=getf(f[x]);
17 }
18 void init()
19 {
20     for(int i=0;i<n;i++)
21     {
22         f[i]=i;
23     }
24     memset(vis,0,sizeof(vis));
25 }
26 bool cmp(node a,node b)
27 {
28     return a.val>b.val;
29 }
30 int main()
31 {
32     while(~scanf("%d%d",&n,&m))
33     {
34         ans=0;
35         init();
36         for(int i=0;i<m;i++)
37         {
38             scanf("%d%d%d",&e[i].l,&e[i].r,&e[i].val);
39         }
40         sort(e,e+m,cmp);
41         for(int i=0;i<m;i++)
42         {
43             int tx=getf(e[i].l);
44             int ty=getf(e[i].r);
45             if(tx!=ty)
46             {
47                 if(!vis[tx]&&!vis[ty])
48                 {
49                     f[tx]=ty;
50                     ans+=e[i].val;
51                 }
52                 else if((!vis[tx]&&vis[ty])||(vis[tx]&&!vis[ty]))
53                 {
54                     f[tx]=ty;
55                     ans+=e[i].val;
56                     vis[tx]=1;
57                     vis[ty]=1;
58                 }
59             }
60             else
61             {
62                 if(!vis[tx])
63                 {
64                     f[tx]=ty;
65                     ans+=e[i].val;
66                     vis[tx]=1;
67                 }
68             }
69         }
70         printf("%d\n",ans);
71     }
72 return 0;
73 }

猜你喜欢

转载自www.cnblogs.com/1013star/p/9558069.html