华为OD机考题——Linux发行版的数量

题目描述

image
image

思路

  该题可用并查集解决,就是求各个子集合的数量,比较并求极值。

代码

#include <iostream>
#include <map>

using namespace std;

const int N = 205;

int x[N][N];

int f[N];
int n;

void init(int n)
{
	for( int i=0; i<n; ++i )
		f[i] = i;
}

int find( int x )
{
	if( x != f[x] )
		return f[x] = find( f[x] );
	return x;
}

void add( int x, int y )
{
	int xf = find(x);
	int yf = find(y);
	if( xf != yf )
		f[y] = x;
}

void read()
{
	cin >> n;
	for (int i = 0; i < n; i++) 
		for (int j = 0; j < n; j++) 
        	cin >> x[i][j];
} 

int main()
{
	read();
	init(n);
	for (int i = 0; i < n; i++) 
		for (int j = i+1; j < n; j++) 
        	if( x[i][j] == 1 )
        		add(i,j);
    
	map<int, int> fc;
    int res = -1;
    
    for (int i = 0; i < n; i++) 
	{
		int f = find(i);
		int exist = fc.count(f);
		if( exist )
		{
			fc[f] = fc[f] + 1;
			res = max( res, fc[f] );
		}else
		{
			fc[f] = 1;
			res = max( res, fc[f] );
		}
    }
    cout << res << '\n';
	return 0;
}
posted @   平安顺遂233  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示