题解:CF2131E Adjacent XOR

· · 题解

题解:CF2131E Adjacent XOR

题目大意

有两个长度为 n 的多重集 a 和 b。你可以将 a_i \oplus a_{i+1},判断是否可以通过此操作将 a 变为 b。

思路

因为它是异或它后面那个数,所以只有后面那个数会对前面那个有影响,所以我们从后往前遍历。在遍历时进行三个判断:

  1. 如果 a_i = b_i,直接跳过。
  2. 如果此时 a_i \ne b_i 并且不管后面那个变或不变这个异或后都无法和 b_i 相等,那么 flag 等于 1,直接退出循环。
  3. 如果 a_i \ne b_i,那就有两个情况,第一种后面那个还不变,那么就是 a_i \oplus a_{i+1},第二个就是后面那个已经变了,并且是可以变成 b 的,那么就是 a_i \oplus b_{i+1},这里为什么是 b_{i+1},因为后面那个已经可以变成 b 了,这样写不仅可以区分两种情况,还可以少些一个数组存原来的数值,更加方便了。

    细节

    可以在开始的时候先判断 a_n 是否等于 b_n,如果不等于直接输出否,因为它后面们有可以异或的,变不了,所以不相等肯定就不行。
    然后在遍历的时候相等或变了之后相等的情况千万不要错写成了直接把 a_i 异或掉,这样写就无法区分两种情况了,所以是直接跳过。

    Code

    
    #include <bits/stdc++.h>
    using namespace std;
    const int N=2e5+5;

int t,n,a[N],b[N];

int read(){ int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x10+c-'0';c=getchar();} return xf; }

int main(){ t=read(); while (t--){ n=read(); for (int i=1;i<=n;i++) a[i]=read(); for (int i=1;i<=n;i++) b[i]=read(); if (a[n]!=b[n]){ cout <<"NO"<<endl; continue; } bool flag=0; for (int i=n-1;i>=1;i--){ if (a[i]==b[i]) continue; else if ((a[i]^a[i+1])==b[i]||(a[i]^b[i+1])==b[i]) continue; else{ flag=1; break; } } if (!flag) cout <<"YES"<<endl; else cout <<"NO"<<endl; } return 0; }