K-Nice
Time Limit: 1 Second Memory Limit: 32768 KB Special Judge
This is a super simple problem. The description is simple, the solution is simple. If you believe so, just read it on. Or if you don’t, just pretend that you can’t see this one.
We say an element is inside a matrix if it has four neighboring elements in the matrix (Those at the corner have two and on the edge have three). An element inside a matrix is called “nice” when its value equals the sum of its four neighbors. A matrix is called “k-nice” if and only if k of the elements inside the matrix are “nice”.
Now given the size of the matrix and the value of k, you are to output any one of the “k-nice” matrix of the given size. It is guaranteed that there is always a solution to every test case.
Input
The first line of the input contains an integer T (1 <= T <= 8500) followed by T test cases. Each case contains three integers n, m, k (2 <= n, m <= 15, 0 <= k <= (n - 2) * (m - 2)) indicating the matrix size n * m and it the “nice”-degree k.
Output
For each test case, output a matrix with n lines each containing m elements separated by a space (no extra space at the end of the line). The absolute value of the elements in the matrix should not be greater than 10000.
Sample Input
2
4 5 3
5 5 3
Sample Output
2 1 3 1 1
4 8 2 6 1
1 1 9 2 9
2 2 4 4 3
0 1 2 3 0
0 4 5 6 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Author: ZHUANG, Junyuan
Source: The 6th Zhejiang Provincial Collegiate Programming Contest
题目大意:我们有一个n*m的矩阵,我们对矩阵里边有4个相邻格子的元素如果是nice格子定义为:这个格子有四个相邻的格子(也就是说不能在边界上),并且其值和其四个相邻格子的值的和相等,辣么这个格子就叫做nice格子。问:给你一个n*m的矩阵,并且已知有k个nice格子,任意输出一个合法的格子。
构建思路过程:
一开始的反应是暴搜+剪枝+剪枝+剪枝+剪枝兴许就可以过了喵~然后开开心心的开始敲代码、敲了半天才反应过来怎么特喵的剪枝啊~然后队友也说他有别的题的思路, 这个题我的暴搜也算结束了,这个时候我仔细的观察第二组样例:
5 5 3
0 1 2 3 0
0 4 5 6 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
其中合法的格子是(4,1)(4,2)(4,3),这三个格子的值都是0,我这才恍然大悟,如果我们在矩阵里边随意挑选k个合法的位子对其赋值为0,并且让其四周都赋值为0,其他的格子都赋值为1就行了啊~!
举例说明:
假如输入是 5 5 1
我们就可以将矩阵赋值为这样:
1 0 1 1 1
0 0 0 1 1
1 0 1 1 1
1 1 1 1 1
1 1 1 1 1
假如是5 5 2:
1 0 0 1 1
0 0 0 0 1
1 0 0 1 1
1 1 1 1 1
1 1 1 1 1
依次类推,并且题目中保证了一定有解,辣么也不用考虑0多赋值的问题了,剩下的部分就是直接敲的部分了。
#include<stdio.h>
#include<string.h>
using namespace std;
int output[25][25];
int n,m,k;
void work(int x,int y,int k)
{
if(k==0)return ;
output[x][y]=0;
output[x-1][y]=0;
output[x+1][y]=0;
output[x][y-1]=0;
output[x][y+1]=0;
if(y+1<m-1)
work(x,y+1,k-1);
else
work(x+1,1,k-1);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&k);
memset(output,1,sizeof(output));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
output[i][j]=1;
}
}
work(1,1,k);
for(int i=0;i<n;i++)
{
for(int j=0;j<m-1;j++)
{
printf("%d ",output[i][j]);
}
printf("%d",output[i][m-1]);
printf("\n");
}
}
}