More is better
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
#include<iostream> #include<stdio.h> #include<algorithm> #define N 10000001 //將一個數定義在預處理部分 using namespace std; int path[N]; int sum[N]; int findroot(int a){int temp=a;while (path[a] != -1){a=path[a];}int temp2;//改進,使樹的高度變矮,寬度增加,方便找根 while (path[temp]!= -1){temp2=path[temp];path[temp]=a;temp=temp2;}return a; }int main (){int n;while (cin>>n){for (int i=1;i<=N;i++){path[i]=-1; sum[i]=1;}int ans=0;int a,b;while (n--){cin >>a>>b;a=findroot(a);b=findroot(b);if (a!=b){path[a]=b;sum[b]+=sum[a];sum[a]=0;} }for (int i=1;i<=N;i++){if (sum[i] > ans)ans =sum[i];}cout<<ans<<endl;} return 0; }
?
跟上一道暢通工程幾乎一樣
加了一個在合并集合時同時合并(加)元素個數的功能
ps:不能想著在找根的過程中數元素個數,因為不一定是葉子,數出來的不對,
轉載于:https://www.cnblogs.com/yexiaoqi/p/7232679.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的More is better的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Azure虚拟机网站部署 防火墙设置
- 下一篇: 中国发表粮食安全白皮书意味着什么?白皮书