NEFU 3题

http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=3

description

The students in computer science college of Huade School of Applied Technology of Harbin Institute of Technology are having the algorithm class, in the class, the teacher come up with questions as following:
In one matrix of N*N, there is one none-negative number in one grid. The teacher wants to know whether have one sub matrix, the sum of all numbers in the sub matrix is equal to K.
							

input

There are several cases.
In the first line of each case is two integers N(N<=50) and K. Then, N lines follows, each line contains N integers, all N*N integers represent the term in matrix.
Proceed to the end of file.

output

For each test case, if there is a sub matrix, the sum of all numbers in the sub matrix is equal to K, output “yes”, otherwise output “no”. The output of one test case occupied exactly one line.

sample_input

3 7
1 2 3
1 2 3
1 2 3

sample_output

no
题目让求一个N*N的矩阵中是否存在一个子矩阵使得该子矩阵中的所有元素的和为K。
如果直接暴力的话会超时。可以构造一个矩阵b[i][j]为0-1行,0-j列的所有元素的和。利用这个矩阵可以求出任意一子矩阵的和,详见代码:
#include <stdio.h>
using namespace std;
int a[55][55];
int main()
{
    int n,m,sum,x,flag;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
            {
                scanf("%d",&x);
                a[i][j]=x+a[i-1][j]+a[i][j-1]-a[i-1][j-1];
            }
        /*for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
                printf("%d ",a[i][j]);
            printf("\n");
        }*/
        flag=1;
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                for(int k=1; k<=i; k++)
                {

                    for(int l=1; l<=j; l++)
                    {
                        sum=a[i][j]+a[i-k][j-l]-a[i][j-l]-a[i-k][j];
                        //printf("(%d)",sum);
                        if(sum==m)
                        {
                            flag=0;
                            break;
                        }
                    }
                    if(flag==0)
                         break;
                }
            }
            if(flag==0)
                break;
        }
        if(flag==0)
            printf("yes\n");
        else
            printf("no\n");
    }
    return 0;
}

你可能感兴趣的:(NEFU 3题)