Educational Codeforces Round 89 C. Palindromic Paths

题目描述

You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number ai,j is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1,1), and it will be moved to the cell (n,m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x,y), then after the move it can be either (x+1,y) or (x,y+1)). The chip cannot leave the matrix.
Consider each path of the chip from (1,1) to (n,m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.

Input

The first line contains one integer t (1≤t≤200) — the number of test cases.
The first line of each test case contains two integers n and m (2≤n,m≤30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers ai,1, ai,2, …, ai,m (0≤ai,j≤1).

Output

For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.

Example

input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
output
0
3
4
4

Note

The resulting matrices in the first three test cases:
Educational Codeforces Round 89 C. Palindromic Paths_第1张图片

题目大意

给出一个矩阵,要从矩阵(1,1)点走到(n,m)点。
我们可以修改矩阵中一些点的值,使得从(1,1)到(n,m)的每一条路组成的所有数字都为回文。

题目分析

以样例四为例:
Educational Codeforces Round 89 C. Palindromic Paths_第2张图片
第一步: 1
第二步: 0 1
第三步: 1 1 0
第四步: 0 1 0
第五步: 0 1 1
第六步: 0 0
第七步: 0
为了能使路径全部为回文,就要让第一步和第七步中的数全部一样,第二步和第六步中的数全部一样,以此类推。。。
1-7需要修改一个数。
2-6需要修改一个数
3-5需要修改两个数
因此答案就为1+1+2=4.
我们只需要用代码实现一下这个过程即可。

代码如下
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include 
#define LL long long
using namespace std;
const int N=65;
int a[N][N];           //存矩阵
vector<int> h[N];      //存每一步可以走到的数
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,m;
		scanf("%d%d",&n,&m);
		for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
		{
			scanf("%d",&a[i][j]);
		}
		
		for(int k=0;k<n+m-1;k++)    //算出每一步可以走到的数,并用h[]储存
		{
			for(int i=0;i<n;i++)
			{
				int j=k-i;
				if(j>=0&&j<m)
				{
					h[k].push_back(a[i][j]);
				}
			}
		}
		int ans=0;
		for(int i=0,j=n+m-2;i<(n+m-1)/2;i++,j--)  //计算相应的两步中1和0的个数
		{
			int a=0,b=0;
			for(int it:h[i])
			{
				if(it) a++;
				else b++;
			}
			for(int it:h[j])
			{
				if(it) a++;
				else b++;
			}
			ans+=min(a,b);   //修改次数即为1和0的较小值
		}
		cout<<ans<<endl;
		for(int i=0;i<65;i++)   //清空h
		h[i].clear();
	}
	return 0;
}

你可能感兴趣的:(Codeforces)