UVA11470 Square Sums【水题】

Do you know that there are squares within a square. This might seem confusing, but take a look at this.
    Suppose you have a square grid of size 5 × 5 completely filled with integers.
在这里插入图片描述
    You can make three squares from the table above... well there are more but we will consider only concentric squares. The squares are denoted using different fonts.
    In this problem you have to find the sum of the numbers of each square.
    For the above case the sums are
5 + 3 + 2 + 7 + 9 + 1 + 4 + 5 + 6 + 1 + 1 + 1 + 4 + 5 + 6 + 3 = 63
7 + 4 + 2 + 3 + 4 + 3 + 4 + 5 = 32
2 = 2
Input
There will be several lines in the input file. Each case starts with an integer n (n ≤ 10) that determines the dimension of the square grid. Each of the next n lines will contain n integers each that will fill the square table in row major order. Input is terminated by a case where n == 0.
Output
Each line of output will start with ‘Case #:’ where # is replaced by the case number. Then you have to output ⌈(n/2)⌉ space separated numbers that will represent the sums from outer to inner. Follow the sample for exact details.
Sample Input
5
5 3 2 7 9
1 7 4 2 4
5 3 2 4 6
1 3 4 5 1
1 4 5 6 3
1
1
0
Sample Output
Case 1: 63 32 2
Case 2: 1

问题链接UVA11470 Square Sums
问题简述:(略)
问题分析
    对于给定的矩阵从外到里一圈一圈地求和,并且输出结果。
    该题的关键是如何控制圈?如何求和?用4个变量(row1,row2,col1,col2)分别表示开始和结束行、开始和结束列,控制和计算就简单了。需要考虑特例,即只有1个元素的矩阵和最后一圈只剩下1个元素的情况。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA11470 Square Sums */

#include <iostream>

using namespace std;

const int N = 10;
int a[N][N];

int main()
{
    int n, caseno = 0;
    while(scanf("%d", &n) != EOF && n) {
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                scanf("%d", &a[i][j]);

        printf("Case %d:", ++caseno);
        int row1 = 0, row2 = n - 1, col1 = 0, col2 = n - 1;
        while(row1 <= row2) {
            int sum = 0;
            if(row1 == row2)
                sum = a[row1][row2];
            else {
                for(int i = row1; i <= row2; i++)
                    sum += a[i][col1] + a[i][col2];
                for(int i = col1 + 1; i < col2; i++)
                    sum += a[row1][i] + a[row2][i];
            }
            printf(" %d", sum);

            row1++, row2--, col1++, col2--;
        }
        printf("\n");
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tigerisland45/p/10358688.html