2018牛客多校训练----Another Distinct Values

链接: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*n的方阵,在方阵上添加0、1、-1,使方阵每行每列的和都不相同。

  思路:

  构造题,正解推公式相当之复杂。但通过找规律可以推出一种构造方法。奇数长度方阵不存在这种情况,可能的行列和范围在-n和n之间,共2n+1中情况。将方阵分为左半边和右半边,构造找规律。

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

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n,i,j,k,cnt0;
        cin>>n;
        if(n%2)
        {
            cout<<"impossible"<<endl;
        }
        else
        {
            cout<<"possible"<<endl;
            cnt0=n/2;
            for(i=0;i<n/2;i++)
            {
                for(j=0;j<n/2;j++)
                {
                    cout<<1<<" ";
                }
                for(k=0;k<cnt0;j++,k++)
                {
                    cout<<0<<" ";
                }
                for(;j<n;j++)
                {
                    cout<<-1<<" ";
                }
                cnt0--;
                cout<<endl;
            }
            cnt0=n/2;
            for(i=0;i<n/2;i++)
            {
                for(j=0,k=0;k<cnt0;j++,k++)
                {
                    cout<<1<<" ";
                }
                for(;j<n/2;j++)
                {
                    cout<<0<<" ";
                }
                for(j=0;j<n/2;j++)
                {
                    cout<<-1<<" ";
                }
                cnt0--;
                cout<<endl;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jinghui_7/article/details/81265356