poj 2443 Set Operation (位操作)
2013-09-27 21:13
162 查看
Set Operation
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; }
相关文章推荐
- 一些有用的位操作
- 简单的位操作
- AVR c语言的位操作
- C# 位操作
- poj 4095(位操作)
- 位操作指令bitwise logical instructions
- poj 3748 位操作
- C 位操作 详解
- 实习生面试题之一 C语言的位操作
- mysql 位操作
- C 位操作
- 用C语言数组实现位操作(位数组)
- 让操作更方便:从传输报文的位操作到byte扩展
- C# 位操作
- STM32的位操作的方法
- 位操作基础篇之位操作全面总结
- 奶牛合作 对于位操作的敏感
- 位操作基础篇之位操作全面总结 .
- 嵌入式经典面试题---C中有关预处理,关键字const、volatile、static,位操作,等等
- 九度OJ 1151 : 位操作练习