3x3 Convolution
题目链接
Problem Description
Given an n×n matrix A and a 3×3 matrix K. These two matrices are very special : they are both non-negative matrices and the sum of all elements in matrix K is 1 (In order to avoid floating-point error, we will give matrix K in a special way in input).
Now we define a function C(A,K), the value of C(A,K) is also a n×n matrix and it is calculated below(we use C to abbreviate C(A,K)):
Cx,y=∑min(n−x+1,3)i=1∑min(n−y+1,3)j=1Ax+i−1,y+j−1Ki,j
Now we define Cm(A,K)=C(Cm−1(A,K),K) and C1(A,K)=C(A,K), Kanade wants to know limt→∞Ct(A,K)
It’s guaranteed that the answer exists and is an integer matrix.
Input
There are T test cases in this problem.
The first line has one integer T.
Then for every test case:
The first line has one integer n.
Then there are n lines and each line has n non negative integers. The j-th integer of the i-th row denotes Ai,j
Then there are 3 lines and each line has 3 non negative integers. The j-th integer of the i-th row denotes K′i,j
Then K could be derived from K′ by the following formula:
Ki,j=K′i,j/(∑x=13∑y=13K′x,y)
1≤T≤100
3≤n≤50
0≤Ai,j≤1000
0≤K′i,j≤1000
∑3x=1∑3y=1K′x,y>0
Output
For each test case, output the answer matrix by using the same format as the matrix A in input.
Sample Input
2
3
1 2 3
4 5 6
7 8 9
3 0 0
0 0 0
0 0 0
3
1 2 3
4 5 6
7 8 9
1 0 0
0 1 0
0 0 0
Sample Output
1 2 3
4 5 6
7 8 9
0 0 0
0 0 0
0 0 0
题意:
见题目。
思路:
发现规律,当K’矩阵中,若有多个元素,则K矩阵中的元素为分数,则当进行多次操作后,最终的矩阵C全为0。当K’矩阵中只有一个元素,则即是将某个元素替换。当若是在原位置替换则矩阵C不变,此时K‘元素中当且仅当i=1,j=1处元素不为0;若是不同位置替换,则经过数次替换,矩阵全为0。
判断,K’矩阵中当且仅当位置(1,1)非0即可。
AC代码:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
int t,n;
int a[55][55],k[55][55];
int main() {
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
int cnt=0;
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
scanf("%d",&a[i][j]);
}
}
for(int i=1; i<=3; i++) {
for(int j=1; j<=3; j++) {
scanf("%d",&k[i][j]);
if(k[i][j]!=0) {
cnt++;
}
}
}
if(cnt==1&&k[1][1]!=0) {
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(j==n)printf("%d",a[i][j]);
else printf("%d ",a[i][j]);
}
printf("\n");
}
} else {
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(j==n)printf("0");
else printf("0 ");
}
printf("\n");
}
}
}
}