Rotation Lock Puzzle

Problem Description
Alice was felling into a cave. She found a strange door with a number square matrix. These numbers can be rotated around the center clockwise or counterclockwise. A fairy came and told her how to solve this puzzle lock: “When the sum of main diagonal and anti-diagonal is maximum, the door is open.”.
Here, main diagonal is the diagonal runs from the top left corner to the bottom right corner, and anti-diagonal runs from the top right to the bottom left corner. The size of square matrix is always odd.



This sample is a square matrix with 5*5. The numbers with vertical shadow can be rotated around center ‘3’, the numbers with horizontal shadow is another queue. Alice found that if she rotated vertical shadow number with one step, the sum of two diagonals is maximum value of 72 (the center number is counted only once).
 
Input
Multi cases is included in the input file. The first line of each case is the size of matrix n, n is a odd number and 3<=n<=9.There are n lines followed, each line contain n integers. It is end of input when n is 0 .
 
Output
For each test case, output the maximum sum of two diagonals and minimum steps to reach this target in one line.
 
Sample Input

5
9 3 2 5 9
7 4 7 5 4
6 9 3 9 3
5 2 8 7 2
9 9 4 1 9
0

 
Sample Output
72 1
 
Source
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=10;
const int maxm=32 + 10;

int n, M[maxn][maxn];
int d[maxn][maxm];      //d[i][j]表示从外往里数第i层,从左上角开始,下标从0开始,顺时针第j个是谁
int Max[maxn];      //Max[i]表示第i层对角线的4个数的和的最大值
int r[maxn];        //r[i]表示第i层转到对角线的4个数的和的最大值时转了多少次

void read()
{
    int i,j;
    for(i= 0; i<n; i++)
        for(j=0; j<n; j++)
            scanf("%d", &M[i][j]);
}

void get_d()
{
    int i,j,m;
    for(i= 0; i<n/2; i++)
    {
        m=0;
        for(j=i; j<n-i; j++) d[i][m++]=M[i][j];
        for(j=i+1; j<n-i; j++) d[i][m++]=M[j][n-1-i];
        for(j=n-2-i; j>=i; j--) d[i][m++]=M[n-1-i][j];
        for(j=n-2-i; j>i; j--) d[i][m++]=M[j][i];
    }
}

void get_Mr()
{
    int i,j;
    for(i= 0; i<n/2; i++)
    {
        int N=(n - i*2) -1;
        int Ma=-1;
        for(j=0; j<N; j++)        //转j次
        {
            int temp=d[i][j] + d[i][j+N] + d[i][j+2*N] + d[i][j+3*N];
            if(temp>Ma)
            {
                Ma=temp;
                Max[i]=temp;
                r[i]=min(j, N-j);
            }
            else if(temp == Ma)
            {
                r[i]=min(r[i], j);
                r[i]=min(r[i], N-j);
            }
        }
    }
}

void solve()
{
    int sum_val=0, sum_rot=0,i;
    for(i= 0; i<n/2; i++) sum_val += Max[i];
    sum_val += M[n/2][n/2];
    for(i= 0; i<n/2; i++) sum_rot += r[i];
    printf("%d %d\n", sum_val, sum_rot);
}

int main()
{
    while(scanf("%d", &n) == 1 && n)
    {
        read();
        get_d();
        get_Mr();
        solve();
    }
    return 0;
}
View Code

 

posted @ 2013-09-09 21:43  1002liu  阅读(269)  评论(0编辑  收藏  举报