poj 2443 Set Operation (位操作)

Set Operation
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 2307   Accepted: 892

Description

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.

Source

POJ Monthly,Minkerui

思路:

开一个a[32][10001]的数组就能保存所有信息了,并且能优化时间了。充分利用一个int能保存32个信息,把矩阵的每列都看做一个二进制数,但是这个数太大,所以需要分n/32+1个数来保存。每次操作时只要对相应的列进行&操作就够了。既节省了空间,有优化了时间,确实蛮经典的。


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
//#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 10005
#define mod 1000000000
#define INF 0x3f3f3f3f
using namespace std;

int n,m,ans,q,flag;
int a[32][maxn];

int main()
{
    int i,j,t,x,y,u,v;
    while(~scanf("%d",&n))
    {
        memset(a,0,sizeof(a));
        for(i=0;i<n;i++)
        {
            scanf("%d",&m);
            x=i/32;
            t=i%32;
            for(j=0;j<m;j++)
            {
                scanf("%d",&u);
                y=u;
                a[x][y]|=(1<<t);
            }
        }
        m=n/32;
        scanf("%d",&q);
        for(i=1;i<=q;i++)
        {
            scanf("%d%d",&u,&v);
            flag=0;
            for(j=0;j<=m;j++)
            {
                if(a[j][u]&a[j][v])
                {
                    flag=1;
                    break ;
                }
            }
            if(flag) printf("Yes\n");
            else printf("No\n");
        }
    }
    return 0;
}





你可能感兴趣的:(poj 2443 Set Operation (位操作))