问题 A: Plus Matrix
题目描述
Given is an N×N matrix C whose elements are non-negative integers. Determine whether there is a pair of sequences of non-negative integers A1,A2,…,AN and B1,B2,…,BN such that Ci,j=Ai+Bj for every (i,j). If the answer is yes, print one such pair.
Constraints
1≤N≤500
0≤Ci,j≤109
输入
Input is given from Standard Input in the following format:
N
C1,1 C1,2 … C1,N
C2,1 C2,2 … C2,N
:
CN,1 CN,2 … CN,N
输出
If no pair A,B satisfies the condition:
Print No in the first line.
No
If some pair A,B satisfies the condition:
In the first line, print Yes. In the second line, print the elements of A, with spaces in between. In the third line, print the elements of B, with spaces in between.
If multiple pairs satisfy the condition, any of them will be accepted.
Yes
A1 A2 … AN
B1 B2 … BN
样例输入 Copy
【样例1】
3
4 3 5
2 1 3
3 2 4
【样例2】
3
4 3 5
2 2 3
3 2 4
样例输出 Copy
【样例1】
Yes
2 0 1
2 1 3
【样例2】
No
题目描述:给定一个矩阵g[][], 找到两个数组a,b 使得a[i] + b[j] = g[i][j] && a[i] >=0, b[j] >= 0
思路:找出g第1行中的最小值, 将他设为a[1], 那么b就是g[i][j] - ai, 再判断是否合法
为什么呢?
如果将所有的A都加上m, 所有的b都减去m, 那么A+B的值是恒定不变的,这样就可以求出每一行的b, 判断入下一列的b是否都相等, 是否合法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 510;
#define int long long
int a[N], b[N], _a[N * N], cnt;
int g[N][N];
signed main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++)
{
int t = 1e9;
for(int j = 1; j <= n; j ++)
{
cin >> g[i][j];
t = min(t, g[i][j]);
}
_a[cnt ++] = t;
}
bool flag = 1;
for(int _i = 0; _i < cnt; _i ++)
{
flag = 1;
for(int i = 1; i <= n; i ++)a[i] = b[i] = -1;
for(int i = 1; i <= n && flag; i ++)
{
if(a[i] == -1 && b[1] == -1 && flag)
{
a[i] = _a[_i];
for(int j = 1; j <= n; j ++)
{
b[j] = g[i][j] - a[i];
if(b[j] < 0)flag = 0;
}
}
else if(a[i] == -1 && b[1] != -1 && flag)
{
int t = g[i][1] - b[1];
for(int j = 2; j <= n && flag; j ++)
{
if(t != g[i][j] - b[j])
flag = 0;
}
if(flag)a[i] = t;
}
}
if(flag)break;
}
if(flag)
{
puts("Yes");
for(int i = 1; i <= n; i ++)cout << a[i] << ' ';
cout << endl;
for(int i = 1; i <= n; i ++)cout << b[i] << ' ';
cout << endl;
}
else puts("No");
return 0;
}

浙公网安备 33010602011771号