集合演算/ OpenJ_Bailian - 2443

あなたは、Nセット、i番目のセットは、(S(i)で表す)がC(I)要素(ここでは「セット」は、完全に数学で定義された「セット」と同じではない、との組が含まれていてもよい与えられます。 2同じ要素)。セット内のすべての要素は、1から10000までの正の数で表され、現在、いくつかのクエリがあります答える必要があります。クエリは、同時に、少なくとも1つのセットに属するかどうかを与えられた二つの要素iとjを決定することです。数k iはまた、S(k)に属するS(k)と要素jに属する(1 <= K <= N)は、その要素が存在する場合、別の言葉では、決定すべきです。

入力

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.

出力

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

サンプル入力

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

サンプル出力

Yes
Yes
No
No

ヒント

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;
}

おすすめ

転載: www.cnblogs.com/Little-Turtle--QJY/p/12519367.html