CS Course
Problem Description
Little A has come to college and majored in Computer and Science.
Today he has learned bit-operations in Algorithm Lessons, and he got a problem as homework.
Here is the problem:
You are giving n non-negative integers a1,a2,⋯,an, and some queries.
A query only contains a positive integer p, which means you
are asked to answer the result of bit-operations (and, or, xor) of all the integers except ap.
Input
There are no more than 15 test cases.
Each test case begins with two positive integers n and p
in a line, indicate the number of positive integers and the number of queries.
2≤n,q≤105
Then n non-negative integers a1,a2,⋯,an follows in a line, 0≤ai≤109 for each i in range[1,n].
After that there are q positive integers p1,p2,⋯,pqin q lines, 1≤pi≤n for each i in range[1,q].
Output
For each query p, output three non-negative integers indicates the result of bit-operations(and, or, xor) of all non-negative integers except ap in a line.
Sample Input
3 3
1 1 1
1
2
3
Sample Output
1 1 0
1 1 0
1 1 0
解题思路:
题目说给n个数,然后让你求去掉一个数剩下的数的 与 或 抑或 的结果。
首先对每个数按位拆分,然后再用一个cnt数组把他们全加起来。
根据与或非的性质,利用cnt数组快速计算结果。
与 所有数该位为1则为1
或 有一个数为1则为1
抑或 奇数个1则为1
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 1e5+10;
using namespace std;
typedef long long ll;
ll a[N];
ll cnt[35] = {0};
ll b[N][35] = {0};
int main()
{
ll n,m;
while(~scanf("%lld %lld",&n,&m))
{
for(int i = 0 ; i < n ; i ++)
scanf("%lld",&a[i]);
memset(cnt,0,sizeof(cnt)); // 记得要初始化
for(int i = 0 ; i < n ; i ++)
{
for(int j = 0 ; j < 35 ; j ++)
{
b[i][j] = (a[i]>>j)&1;
cnt[j] += b[i][j];
}
}
for(int i = 0 ; i < m ; i ++)
{
ll tmp;
scanf("%lld",&tmp);
tmp --;
for(int j = 0 ; j < 35 ; j ++)
{
cnt[j] -= b[tmp][j];
}
ll ans1 = 0,ans2 = 0,ans3 = 0;
ll tmp1 = 1;
for(int j = 0 ; j < 35 ; j ++)
{
if(cnt[j] == n-1)
ans1 += tmp1;
if(cnt[j] > 0)
ans2 += tmp1;
if(cnt[j] % 2)
ans3 += tmp1;
tmp1 <<= 1;
}
printf("%lld %lld %lld\n",ans1,ans2,ans3);
for(int j = 0 ; j < 35 ; j ++)
{
cnt[j] += b[tmp][j];
}
}
}
}