Set Operation
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
|
题意:
给你n(n<=1000)个集合(集合中可以出现相同的元素)。和n个集合中的元素。集合元素的取值范围为[1,10000]。再给你两个元素a和b。若a,b在同一个集合中输出Yes。否则输出No。
思路:
开始想。用一个二维数组来记录两个数之间的关系。但这样光处理关系时间复杂度已经很高了。而且内存也开不下。
后来想给每个集合建个并查集。不过这样查找效率有很低了。后来瞄了下别人的标题。恍然大悟。可以状态压缩呀。
但由于n比较大所以需要用到30多个int来存。每一个int存30位。这样一来后就简单多了。对于[1,10000]中的每个数建立一个状态。对应位置为1表示在对应集合。反之。这样一来只需把a,b状态数组按位与就行了。不为0 说明在同一集合。反之。位运算确实很好用!
由于输入规模比较大。可以输入优化。
详细见代码:
#include<algorithm>
#include<string.h>
#include<iostream>
#include<stdio.h>
using namespace std;
int state[10010][40];
int main()
{
int n,c,d,i,j,q,a,b,lim;
while(~scanf("%d",&n))
{
memset(state,0,sizeof state);
for(i=0;i<n;i++)
{
scanf("%d",&c);
for(j=0;j<c;j++)
{
scanf("%d",&d);
state[d][i/30]|=1<<(i%30);
}
}
scanf("%d",&q);
lim=n/30;
while(q--)
{
scanf("%d%d",&a,&b);
for(i=0;i<=lim;i++)
if(state[a][i]&state[b][i])
{
printf("Yes\n");
break;
}
if(i>lim)
printf("No\n");
}
}
return 0;
}