CS Course 位运算

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.

2n,q105

Then n non-negative integers a1,a2,,an follows in a line, 0ai109 for each i in range[1,n].

After that there are q positive integers p1,p2,,pqin q lines, 1pin 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


第一次见这种题,对于位运算,我真的很迷。这次用前缀后缀写出来了。

还是经过学长说了一次才明白。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
typedef long long LL;
using namespace std;
long long a[100010];

long long p1[100010],s1[100010];// &的前缀,后缀

long long p2[100010],s2[100010];// | 的前缀,后缀
int main()
{
    int n,q,p;
    long long ans1;
    while(scanf("%d %d",&n,&q)!=EOF){
            ans1=0;
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
            if(i==1){//算前缀
                p1[i]=p2[i]=a[i];
            }
            else {
                p1[i]=(p1[i-1]&a[i]);
                p2[i]=(p2[i-1]|a[i]);
            }
            ans1=a[i]^ans1;
        }
        for(int i=n;i>=1;i--){//算后缀
            if(i==n){
                s1[i]=s2[i]=a[i];
            }
            else {
                s1[i]=(s1[i+1]&a[i]);
                s2[i]=(s2[i+1]|a[i]);
            }
        }
        for(int i=1;i<=q;i++){
            scanf("%d",&p);
            if(p==1){
                printf("%lld %lld %lld\n",s1[2],s2[2],ans1^a[p]);
            }
            else if(p==n){
                printf("%lld %lld %lld\n",p1[p-1],p2[p-1],ans1^a[p]);
            }
            else {
                printf("%lld %lld %lld\n",p1[p-1]&s1[p+1],p2[p-1]|s2[p+1],ans1^a[p]);
            }
        }
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/sinat_40948489/article/details/80412479
cs
今日推荐