您的位置:首页 > 其它

HDU 1856 More is better(求最大秩的集合 )

2015-09-13 20:54 369 查看
题目地址:点击打开链接

题意:给一群人挑出来人数最多的一群

思路:求最大秩的集合

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>

using namespace std;

const int maxn = 10000010;
int pre[maxn],num[maxn];

int find(int x)
{
int r = x,i = x,j;
while(pre[r] != r)
{
r = pre[r];
}
while(pre[i] != r)//路径压缩
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}

/*int find(int x)
{
if(pre[x] != x)
return find(pre[x]);
return x;
}*/
//没路径压缩会超时

/*if(find(x) != find(y))
{
pre[find(y)] = find(x);
num[find(x)] += num[find(y)];
}*/
void join(int x,int y)
{
//上面一部分是错的,没看出来原因,这段代码效率也不高,find函数执行了6次,下面只执行了2次
int p = find(x);
int q = find(y);
if(p != q)
{
pre[p] = q;
num[q] += num[p];
}
}

int main()
{
int n,max1,i,x,y;
while(scanf("%d",&n) != EOF)
{
if(n == 0)
{
printf("1\n");
continue;
}
max1 = 0;
for(i=1; i<=maxn; i++)
{
pre[i] = i;
num[i] = 1;
}
for(i=0; i<n; i++)
{
scanf("%d%d",&x,&y);
if(max1 < x)
max1 = x;
else if(max1 < y)
max1 = y;
join(x,y);
}
int max2 = 0;
for(i=1; i<=max1; i++)
{
if(num[i] > max2)
max2 = num[i];
}
//加个条件判断pre[i] == i也行
printf("%d\n",max2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: