Set Operation / OpenJ_Bailian - 2443

You are given N sets, the i-th set (represent by S(i)) have C(i) element (Here "set" isn't entirely the same as the "set" defined in mathematics, and a set may contain two same element). Every element in a set is represented by a positive number from 1 to 10000. Now there are some queries need to answer. A query is to determine whether two given elements i and j belong to at least one set at the same time. In another word, you should determine if there exist a number k (1 <= k <= N) such that element i belongs to S(k) and element j also belong to S(k).

Input

First line of input contains an integer N (1 <= N <= 1000), which represents the amount of sets. Then follow N lines. Each starts with a number C(i) (1 <= C(i) <= 10000), and then C(i) numbers, which are separated with a space, follow to give the element in the set (these C(i) numbers needn't be different from each other). The N + 2 line contains a number Q (1 <= Q <= 200000), representing the number of queries. Then follow Q lines. Each contains a pair of number i and j (1 <= i, j <= 10000, and i may equal to j), which describe the elements need to be answer.

Output

For each query, in a single line, if there exist such a number k, print "Yes"; otherwise print "No".

Sample Input

3
3 1 2 3
3 1 2 5
1 10
4
1 3
1 5
3 5
1 10

Sample Output

Yes
Yes
No
No

Hint

The input may be large, and the I/O functions (cin/cout) of C++ language may be a little too slow for this problem.

题意

输入一个整数N表示N个集合
接下来N行每行先输入一个整数C表示某个集合的数字个数
然后输入C个整数表示这个集合的所有元素
接下来输入一个整数q
然后是q行
每行两个整数x y
判断x 与 y是否可以属于同一个集合
如果可以输出Yes否则输出No
N <= 1000, C <= 10000 , x, y <= 10000, Q <= 200000

题解

用 bitset
C++的 bitset 在 bitset 头文件中,它是一种类似数组的结构,它的每一个元素只能是0或1,每个元素仅用1bit空间。
本体用到: .set()    .test()
~~具体可看到其它博客~~

代码

#include<bits/stdc++.h>
using namespace std;

int n, m, x, y;
bitset<3010> bit[10010];

int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
        scanf("%d", &x);
        for(int j = 1; j <= x; j++){
            scanf("%d", &y);
            bit[y].set(i);//y下标中, 第i个位置的下标设为1, 表示y在第i组中
        }
    }
    scanf("%d", &m);
    for(int i = 1; i <= m; i++){
        scanf("%d%d", &x, &y);
        for(int j = 1; j <= n; j++){//每个数组遍历一遍, 找有没有符合条件的数组
            if(bit[x].test(j) && bit[y].test(j)){//x, y的下标j是否都为1, 表示它们是否都在同一组内
                printf("Yes\n");
                x = -1;//标记一下
                break;
            }
        }
        if(x != -1)
            printf("No\n");
    }
    return 0;
}
上一篇:There Are Two Types Of Burgers (Educational Codeforces Round 71)


下一篇:UVA - 10462 Is There A Second Way Left?