您的位置:首页 > 其它

1118. Birds in Forest (25)

2017-02-27 19:04 495 查看
并查集

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int pre[10005];
vector<bool> visited(10005,false);
int findroot(int t)
{
if (pre[t] != t) pre[t] = findroot(pre[t]);
return pre[t];
}
void join(int x, int y)
{
int fx = findroot(x);
int fy = findroot(y);
if (fx != fy)
{
pre[max(fx, fy)] = min(fx, fy);
}
}

int main()
{
int N;
cin >> N;
for (int t = 0;t < 10005;t++)
pre[t] = t;
while (N--)
{
int n;
cin >> n;
if (n == 0) continue;
int x, y;
cin >> x;
visited[x] = true;
while (--n)
{
cin >> y;
join(x, y);
visited[y] = true;
}
}
int cnt1 = 0,cnt2=0;
for (int t = 0;t < 10005;t++)
{
if (visited[t])
{
cnt2 = max(cnt2, t);
if (pre[t] == t)
cnt1++;
}
}

cin >> N;
cout << cnt1 << " " << cnt2 << endl;
while (N--)
{
int a, b;
cin >> a >> b;
if (findroot(a) == findroot(b))
cout << "Yes" << endl;
else cout << "No" << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT-甲