[广西邀请赛 - E] [HDU] 6186 - CS Course - 思维 - 位运算 or 前缀和和后缀和

我多久没更新了来着.......?


CS Course

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 282    Accepted Submission(s): 137


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.

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,,pq in 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
 

Source
 


给你n个数a_1 ~ a_n和q次询问,每次询问给你一个数x,输出  所给你的数中,除了a_x数外的剩下数字的 &, | , ^。


对于异或运算,直接算出所有数字的异或后再异或一次a_x

原理大概就是 a ^ b ^ b = a(这TM叫什么原理)



对于& 和 | 有两种解法



解法一 

先预处理一发所给数列的前缀 &,| 和后缀 &,|,然后直接查询x - 1的前缀&以及x + 1的后缀&,再算一次&就出来了,|也是同理。不过要注意一下初始化的不同



#include <bits/stdc++.h>
using namespace std;

const int N = 100010;

int ma[N];
int a1[N], a2[N];
int b1[N], b2[N];
int c;

int main()
{
    int n, m;

    while(scanf("%d%d", &n, &m) == 2){
        for(int i = 1; i <= n; i ++){
            scanf("%d", &ma[i]);
        }
        a1[0] = (1 << 31) - 1;/// & 运算的初始值要每一位都为1
        b1[0] = 0;
        c = 0;
        for(int i = 1; i <= n; i ++){
            a1[i] = a1[i - 1] & ma[i];
            b1[i] = b1[i - 1] | ma[i];
            c ^= ma[i];
        }
        a2[n + 1] = (1 << 31) - 1;
        b2[n + 1] = 0;
        for(int i = n; i > 0; i --){
            a2[i] = a2[i + 1] & ma[i];
            b2[i] = b2[i + 1] | ma[i];
        }
        for(int i = 0; i < m; i ++){
            int x;

            scanf("%d", &x);
            printf("%d %d %d\n", a1[x - 1] & a2[x + 1], b1[x - 1] | b2[x + 1], c ^ ma[x]);
        }
    }

    return 0;
}

解法二

开一个cnt数组计数,cnt[i]表示 二进制表示 第 i 位为 1 的数字的个数。

然后预处理一发所有数据的 & 和 |  ,分别记作 A, B


然后我们先看 & 操作

如果A 的二进制第i位为1,那么说明所有数的第i位都为1,那么就无影响







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值