牛客网暑期ACM多校训练营(第四场)D Another Distinct Values(构造)

本文介绍了一种算法,用于构造一个n×n的矩阵,确保每行每列的和各不相同。文章详细解释了该问题的解决思路,并给出了解决方案的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述 

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的矩阵,保证每行每列的值都不相同。

通过n == 2,可以推出n == 3的时候,需要新加入两个数,但是添加1构成3就没法构成-2,添加-1构成-2就得不到3,以此类推n为奇数的情况都是不可以的,n为偶数时,只需要构造每行每列的1跟-1的值不一样就OK了,可以先空出左下对角线,上三角填充1,下三角填充0,然后对角线0,1平分即可。

代码实现:

/*
Look at the star
Look at the shine for U
*/ 

#include<bits/stdc++.h>
#define sl(x) scanf("%lld",&x)
using namespace std;
typedef long long ll;
const int N = 1e6+5;
const ll mod = 1e9+7;
const ll INF = 1e18;
int s[205][205];
int main()
{
	int n,i,j,k,t;
	scanf("%d",&t);
	while(t--)
	{
		memset(s,0,sizeof(s));
		scanf("%d",&n);
		if(n&1) puts("impossible");
		else
		{
			puts("possible");
			for(i = 0;i < n-1;i++)
				for(j = 0;j < n-i-1;j++)
					s[i][j] = 1;
					
			for(i = 1;i < n;i++)
				for(j = n-1;j >= n-i;j--)
					s[i][j] = -1;
					
			for(i = n-1;i >= n/2;i--) s[i][n-i-1] = 1;
			for(i = 0;i < n;i++)
			{
				for(j = 0;j < n;j++)
				{
					if(j) printf(" "); printf("%d",s[i][j]);
				}
				puts("");
			}
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值