1004 zxa and xor

来源:互联网 发布:域名com cn net的区别 编辑:程序博客网 时间:2024/06/06 07:46

这一题可以通过模拟进行处理。首先要明白异或运算的一个性质就是同一个数异或两次就没有影响了。开两个数组,第一个a存第i个数的数值,另一个b数组存除去第i个数以外所有的数按题目中运算得到的结果。然后计算最开始的值sum。每次修改j将a[j]修改,再将b[j]^sum,更新b[j],在计算b[j]^sum,然后将除了j以外的b数组在更新就行了。这样复杂度为O(n*(m + n))。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int a[20002], b[20002];int main(){    int T;    scanf("%d", &T);    while(T--) {        memset(a, 0, sizeof(a));        memset(b, 0, sizeof(b));        int n, m, sum = 0;        scanf("%d%d", &n, &m);        for(int i = 0; i < n; ++i) {            scanf("%d", &a[i]);        }        for(int i = 0; i < n - 1; ++i) {            for(int j = i + 1; j < n; ++j) {                b[i] ^= (a[i] + a[j]);                b[j] ^= (a[i] + a[j]);                sum ^= (a[i] + a[j]);            }        }        for(int i = 0; i < m; ++i) {            int x, y, t = 0;            scanf("%d%d", &x, &y);            for(int j = 0; j < n; ++j) {                if(j != x - 1) {                    t ^= (y + a[j]);                    b[j] = b[j] ^ (a[j] + a[x - 1]) ^ (a[j] + y);                }            }            sum = sum ^ b[x - 1] ^ t;            b[x - 1] = t;            a[x - 1] = y;            printf("%d\n", sum);        }    }    return 0;}

0 0