codeforces 1016D Vasya And The Matrix 异或 构造

https://vjudge.net/problem/CodeForces-1016D
在这里插入图片描述题目大意:问你能否构造出一个 n m n*m 的矩阵,使得第 i i 行元素的异或和等于 a i a_i ,第 i i 列元素的异或和等于 b i b_i ,若能则输出矩阵每一个元素的值。

思路:其实这题巨水。首先很容易看出有解必须满足: a 1 a n b 1 b m = 0 a_1\oplus……\oplus a_n\oplus b_1\oplus……\oplus b_m=0 ,然后考虑如何构造。首先前 n 1 n-1 行、 m 1 m-1 列的全部元素都搞成 0 0 ,然后第 i i 行的最后一个元素为 a i a_i ,第 i i 列的最后一个元素为 b i b_i ,显然,除了 ( n , m ) (n,m) 这个位置的元素对应两个值,其它位置的值都满足题意,现在只考虑这个位置:(1)仅考虑列,假设此处的值为 t 1 t_1 ,显然要满足: a 1 a n 1 t 1 = b m a_1\oplus……\oplus a_{n-1} \oplus t_1=b_m ;(2)仅考虑行,假设此处的值为 t 2 t_2 ,显然要满足: b 1 b m 1 t 2 = a n b_1\oplus……\oplus b_{m-1}\oplus t_2=a_n 。因为疑惑满足交换律,所以我们可以得到:
t 1 = a 1 a n 1 b m t_1=a_1\oplus……\oplus a_{n-1} \oplus b_m
t 2 = b 1 b m 1 a n t_2=b_1\oplus……\oplus b_{m-1}\oplus a_n
我们将它们异或起来,可以得到:
t 1 t 2 = a 1 a n b 1 b m = 0 t_1\oplus t_2=a_1\oplus……\oplus a_n\oplus b_1\oplus……\oplus b_m=0
由此可得 t 1 = t 2 t_1=t_2 ,也就是说右下角这个值也可以唯一确定,所以构造是满足题意的。

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

int n,m;
int a[105],b[105];

int main()
{
    scanf("%d%d",&n,&m);
    int ans=0;
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]),ans^=a[i];
    for(int i=0;i<m;i++)
        scanf("%d",&b[i]),ans^=b[i];
    if(ans)
        printf("NO\n");
    else
    {
        printf("YES\n");

        ans=0;
        for(int i=0;i<n-1;i++)
        {
            for(int j=0;j<m-1;j++)
                printf("0 ");
            printf("%d\n",a[i]);
            ans^=a[i];
        }
        for(int i=0;i<m-1;i++)
            printf("%d ",b[i]);
        ans^=b[m-1];
        printf("%d\n",ans);
    }
    return 0;
}

发布了677 篇原创文章 · 获赞 30 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/104057426