题目:
链接:https://www.nowcoder.com/acm/contest/142/D
来源:牛客网
题目描述
Chiaki has an n x n matrix. She would like to fill each entry by -1, 0 or 1 such that r1,r2,...,rn,c1,c2, ..., cn are distinct values, where ri be the sum of the i-th row and ci be the sum of the i-th column.
输入描述:
There are multiple test cases. The first line of input contains an integer T (1 ≤ T ≤ 200), indicating the number of test cases. For each test case: The first line contains an integer n (1 ≤ n ≤ 200) -- the dimension of the matrix.
输出描述:
For each test case, if no such matrix exists, output ``impossible'' in a single line. Otherwise, output ``possible'' in the first line. And each of the next n lines contains n integers, denoting the solution matrix. If there are multiple solutions, output any of them.
示例1
输入
2 1 2
输出
impossible possible 1 0 1 -1
思路:
我一开始试了一下n=3,发现不行,于是就猜测只有2可以,交了一发,通过了50%。所以我猜测只有偶数可以,奇数都不行。经过队友验证发现确实如此。然后我们把n=4的情况弄了出来。
中间空白部分放n=2的情况就行。因为n=2的情况时,最大只有2,所以我们可以放心地用3,4。我们可以发现,一个图里既然有了n,那么最小一定是-n+1,而不是-n,所以外圈放两个最大的n,n-1,两个最小的,-n+1,-n+2,其他排都是0,这样就可以在空的部分放n=n-2时的情况了,不断递归就行。
比如n=4的完整的图是
再比如6的时候,也是如此。
代码:
#include<iostream>
using namespace std;
int a[201][201];
int N;
int k;
void dfs(int n)
{
for(int i=k;i<=N-k+1;i++){
for(int j=k*2-1;j<=N;j++){
a[i][j]=-1;
}
}
for(int j=k*2-1;j<=N;j++){
a[k][j]=1;
}
for(int i=k;i<N-k+1;i++){
a[i][k*2-1]=1;
}
a[N-k+1][k*2-1]=0;
k++;
if(n==2)return;
dfs(n-2);
}
int main()
{
int t;
cin>>t;
while(t--){
cin>>N;
if(N%2==1)cout<<"impossible"<<endl;
else{
cout<<"possible"<<endl;
k=1;
dfs(N);
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
}
return 0;
}