Given an n*n matrix A, whose entries Ai,j are integer numbers ( 0 <= i < n, 0 <= j < n ). An operation SHIFT at row i ( 0 <= i < n ) will move the integers in the row one position right, and the rightmost integer will wrap around to the leftmost column.
max0<=j< n{Cj|Cj=Σ0<=i< nAi,j} Input The input consists of several test cases. The first line of each test case contains an integer n. Each of the following n lines contains n integers, indicating the matrix A. The input is terminated by a single line with an integer −1. You may assume that 1 <= n <= 7 and |A i,j| < 10 4. Output For each test case, print a line containing the minimum value of the maximum of column sums. Sample Input Sample Output 输入一个n×n的矩阵,可以对矩阵的每行进行任意次的循环右移操作,行的每一次右移后,计算矩阵中每一列的和的最大值,输出这些最大值中的最小值 |
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 1010;
const int inf = 0x3f3f3f3f;
int n;
int a[maxn][maxn];
int ans;
void init(int x)//对行a[x][]循环右移一次
{
int t=a[x][n-1];
for(int j=n-1; j>0; j--)
{
a[x][j]=a[x][j-1];
}
a[x][0]=t;
}
void dfs(int x)
{
if(x==n)
{
int maxSum=-inf;//列和的最大值
for(int i=0; i<n; i++)
{
int sum=0;
for(int j=0; j<n; j++)
{
sum+=a[j][i];
}
maxSum=max(sum,maxSum);
}
ans=min(maxSum,ans);//保存列和最大值中的最小值
//printf("ans = %d %d\n",ans,x);
}
else
{
for(int i=0; i<n; i++)//每一行都循环右移n次
{
init(x);
//printf("an = %d %d\n",ans,x);
dfs(x+1);
}
}
}
int main()
{
while(scanf("%d",&n),n!=-1)
{
memset(a,0,sizeof(a));
ans=inf;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
scanf("%d",&a[i][j]);
}
}
dfs(0);
printf("%d\n",ans);
}
return 0;
}