[ARC115B] Plus Matrix

· · 题解

题面

[ARC115B] Plus Matrix

分析

通过手算一下样例发现如果有解,那 C 中同一列的任意值与其右侧相邻的值的差相同,同一行的任意值与其右侧相邻的值的差也一定相同。

即:

C_{i,j}-C_{i,j-1}=C_{i-1,j}-C_{i-1,j}(2\le i,j \le n) C_{i-1,j}-C_{i,j}=C_{i-1,j-1}-C_{i,j-1}(2\le i,j \le n)

如果不满足上式,则无解。

因为 A,B 数列中的元素都为非负整数,同时容易发现 C_{i,i}=A_i+B_i, 所以只要让 A 或者 B 取最小的行或者列(此处最小意为各个值都为最小的),那么另一个数列就直接求出来了。

Code

#include<bits/stdc++.h>
using namespace std;
int c[510][510];
int aa[510][510],bb[510][510];
int a[510],b[510];
int n;
int main()
{
    scanf("%d",&n);
    int Min=0x7f7f7f7f,x,y;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&c[i][j]);
            if(Min>c[i][j])
            {
                Min=c[i][j];
                x=i,y=j;
            }
            aa[i][j]=c[i][j]-c[i][j-1];
            bb[i][j]=c[i][j]-c[i-1][j];
        }
    }
    for(int i=2;i<=n;i++)
    {
        for(int j=2;j<=n;j++)
        {
            if(aa[i][j]!=aa[i-1][j]||bb[i][j]!=bb[i][j-1])
            {
                printf("No");
                return 0;
            }
        }
    }
    puts("Yes");
    for(int i=1;i<=n;i++)
    {
        b[i]=c[x][i];
    }
    for(int i=1;i<=n;i++)
    {
        a[i]=c[i][i]-b[i];
        printf("%d ",a[i]);
    }
    putchar(10);
    for(int i=1;i<=n;i++)
    {
        printf("%d ",b[i]);
    }   
    return 0;

}