UVA11470 Square Sums水题

Posted tigerisland45

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("
");
    }

    return 0;
}

以上是关于UVA11470 Square Sums水题的主要内容,如果未能解决你的问题,请参考以下文章

POJ2602 Superlong sums水题

uva:10487 - Closest Sums(二分查找)

UVA10487 Closest Sums暴力+二分

uva-10487 - Closest Sums

K Smallest Sums UVA - 11997

UVA10616 Divisible Group Sums组合+0-1背包