天天看点

PAT (Advanced Level) Practise 1118 Birds in Forest (25)

1118. Birds in Forest (25)

时间限制

150 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number N (<= 104) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B1 B2 ... BK

where K is the number of birds in this picture, and Bi's are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 104.

After the pictures there is a positive number Q (<= 104) which is the number of queries. Then Q lines follow, each contains the indices of two birds.

Output Specification:

For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line "Yes" if the two birds belong to the same tree, or "No" if not.

Sample Input:

4

3 10 1 2

2 3 4

4 1 5 7 8

3 9 6 4

2

10 5

3 7

Sample Output:

2 10

Yes

No

用并查集合并一下,最大的树的数量就是点数减去合并次数。

#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define ff first
#define ss second
#define mp(i,j) make_pair(i,j)
#define pb push_back
#define pii pair<int,LL>
#define in(x) scanf("%d", &x);
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-4;
const int INF = 0x7FFFFFFF;
const int mod = 998244353;
const int N = 1e5 + 10;
int n, m, x, y, fa[N], f[N];
int len = 0, cnt = 0;

int get(int x)
{
  return x == fa[x] ? x : fa[x] = get(fa[x]);
}

int main()
{
  rep(i, 1, N - 1) fa[i] = i;
  scanf("%d", &n);
  rep(i, 1, n)
  {
    scanf("%d", &m);
    rep(j, 1, m)
    {
      scanf("%d", &y); 
      f[y] = 1;  len = max(len, y);
      if (j == 1) { x = y; continue; }
      int fx = get(x), fy = get(y);
      if (fx == fy) continue;
      fa[fx] = fy;  cnt--;
    }
  }
  printf("%d %d\n", len + cnt, len);
  scanf("%d", &n);
  rep(i, 1, n)
  {
    scanf("%d%d", &x, &y);
    printf("%s\n", get(x) == get(y) ? "Yes" : "No");
  }
  return 0;
}