2017.12.23
之前一直WA,后来百度才知道当输入0时应该输出1
因为此时大家都没有朋友,只能选一个人
#include <iostream>
#include <algorithm>
#include <cstring>
#include <utility>
#include <cstdio>
using namespace std;
#define MAX 10000000 + 5
int pre[MAX];
int con[MAX];
void init(int n){
for(int i = 1; i <= n; i++)
pre[i] = i;
}
int find(int x){
int root = x;
while(root != pre[root])
root = pre[root];
while(x != root){
int t = pre[x];
pre[x] = root;
x = t;
}
return root;
}
void join(int x, int y){
int xx = find(x);
int yy = find(y);
if(xx != yy)
pre[xx] = yy;
}
int main(){
int n;
int a, b;
int maxnum = 0;
int maxout;
int i, j;
while(cin >> n){
maxnum = 0;
if(n == 0)
{
cout << "1" << endl;
continue;
}
init(MAX);
for(i = 0; i < n; i++){
scanf("%d%d", &a, &b);
maxnum = max(maxnum, a);
maxnum = max(maxnum, b);
join(a, b);
}
memset(con, 0, sizeof(con));
for(i = 1; i <= maxnum; i++)
con[find(i)] = 1;
maxout = 0;
int sum;
for( i = 1; i <= maxnum; i++){
if(con[i] == 0)
continue;
sum = 0;
for( j = 1; j <= maxnum; j++){
if(pre[j] == i)
sum++;
}
if(sum > maxout)
maxout = sum;
}
printf("%d\n", maxout);
}
return 0;
}
该程序使用C++编程,通过并查集算法解决寻找给定朋友关系中最大的团体问题。在输入为0时,程序会输出1,表示没有朋友关系。程序读取朋友关系,初始化并查集,然后连接朋友,最后找出最大团体的大小。
308

被折叠的 条评论
为什么被折叠?



