題目鏈接:http://zju.acmclub.com/index.php?app=problem_title&id=1&problem_id=21376 ACM破50啦!!目標150!!
題目描述
小明所在的學校有N個學生,形成M個俱樂部。每個俱樂部裏的學生有着一定相似的興趣愛好,形成一個朋友圈。一個學生可以同時屬於若干個不同的俱樂部。根據“我的朋友的朋友也是我的朋友”這個推論可以得出,如果A和B是朋友,且B和C是朋友,則A和C也是朋友。請編寫程序計算最大朋友圈中有多少人。
輸入格式
輸入包含多組測試數據,每組輸入的第一行包含兩個正整數N(<=30000)和M(<=1000),分別代表學校的學生總數和俱樂部的個數。後面的M行每行按以下格式給出1個俱樂部的信息,其中學生從1~N編號:
第i個俱樂部的人數Mi(空格)學生1(空格)學生2……學生Mi
輸出
對於每組輸入,輸出一個整數,表示在最大朋友圈中有多少人。
樣例輸入
7 4
3 1 2 3
2 1 4
3 5 6 7
1 6
10 1
1 7
樣例輸出
4
1
測試文件:/0.out 結果:答案正確 測試文件:/2.out 結果:答案錯誤 =======原因====== 當參考答案輸出: 573 -------時--------- 你的程序輸出: 426 ================= 測試文件:/1.out 結果:答案正確自己出了一個稍微大一點的數據,就發現了問題所在。
比如用下面的數據:
100 8
3 1 2 3
2 1 4
3 5 6 7
1 6
4 5 6 7 8
3 1 2 3
2 3 5
7 1 2 3 4 5 6 7
最後set[i]的值爲(從1開始) 1 1 1 1 1 1 1 5
8的父親是5,原因是8就出現一次,沒有出現第二次,所以它的父親就是5,而不是新的父親1,原因是路徑還沒有壓縮!!
所以在統計最大值時應該使用改進後的代碼。
代碼如下:
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<iomanip>
using namespace std;
const int MAXN = 30001;
int set[MAXN];
int height[MAXN];
void init(int n)
{
for (int i = 0; i <= n; i++)
{
set[i] = i;
height[i] = 0;
}
}
int cha(int x)//返回x所在集合的根
{
if (set[x] == x)
return x;
else
return set[x] = cha(set[x]);
}
void unite(int x, int y)
{
x = cha(x);
y = cha(y);
if (x == y)
return;
if(height[y]>height[x])
{
set[x] = y;
}
else
{
set[y] = x;
if (height[x] == height[y])
height[x]++;
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("D:\\in.txt", "r", stdin);
freopen("D:\\out.txt", "w", stdout);
#endif
int n(0), m(0);
while (cin >> n >> m)
{
init(n);
for (int i = 0; i < m; i++)
{
int k;
cin >> k;
int t;
int pre = -1;
for (int i = 0; i < k; i++)
{
cin >> t;
if (pre != -1)
{
unite(pre, t);
}
pre = t;
}
}
/*vector<int> coll;
for (int i = 1; i <= n; i++)
{
if (set[i] == i)
coll.push_back(i);
}
vector<int> vec;
for (int i = 0; i < coll.size(); i++)
{
int cnt = count(set + 1, set + n + 1, coll[i]);
vec.push_back(cnt);
}
cout << *max_element(vec.begin(), vec.begin() + vec.size()) << endl;*/
map<int, int> m;
int maxx = -1;
for (int i = 1; i <= n; i++)
{
int fa = cha(i);
m[fa]++;
if (m[fa] > maxx)
maxx = m[fa];
}
cout << maxx << endl;
}
return 0;
}