题目:
给出m个员工会的语言,现要求每名员工之间都要能够写信相互交流( 可以通过他人翻译)。员工可以通过学习来学会新的语言,学习成本假设为1,求最小的学习成本。
思路:
运用并查集的思路,将所有能够使用同一种语言的人并到同一个树里,最后再检查图里面有多少棵树就可以的到答案( 应该注意存在不会任何语言的员工,所以需要将所有员工掌握的语言也记下来,最后再进行特殊判断,不然会wa 。)
代码:
#include <bits/stdc++.h>
using namespace std;
const int MaxN = 101;
int Map[ MaxN ][ MaxN ];// person // language
int father[ MaxN ];
int num[ MaxN ];
int finding( int need ) {
return father[ need ] = ( father[ need ] == need ) ? need : finding( father[ need ] );
}
int main( ) {
int N, M;
int i, j, k;
int x, y;
int last;
int ans = 0;
cin >> N >> M;
for ( i = 1; i <= N; i++ ) {
cin >> j;
num[ i ] = j;
while ( j -- ) {
cin >> k;
Map[ i ][ k ] = 1;
}
}
for ( i = 1; i <= N; i++ ) {
father[ i ] = i ;
}
for ( i = 1; i <= M; i++ ) {
last = -1;
for ( j = 1; j <= N; j++ ) {
if ( Map[ j ][ i ] ) {
if ( last == -1 ) {
last = j;
father[ j ] = finding( j );
} else {
father[ j ] = finding ( j );
if ( father[ last ] != father[ j ] ) {
father[ father[ j ] ] = father[ last ];
}
}
}
}
}
last = 1;
for ( i = 1; i <= N; i++ ) {
if ( father[ i ] == i ) {
if ( num[ i ] == 0 ) {
ans ++;
continue;
}
if ( last ) {
last = 0;
} else {
ans ++;
}
}
}
cout << ans << endl;
}