HDU1559(二维前缀和模板 Java&C++)

HDU1559(二维前缀和模板)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1559

Problem Description

给你一个m×n的整数矩阵,在上面找一个x×y的子矩阵,使子矩阵中所有元素的和最大。

Input

输入数据的第一行为一个正整数T,表示有T组测试数据。每一组测试数据的第一行为四个正整数m,n,x,y(0<m,n<1000 AND 0<x<=m AND 0<y<=n),表示给定的矩形有m行n列。接下来这个矩阵,有m行,每行有n个不大于1000的正整数。

Output

对于每组数据,输出一个整数,表示子矩阵的最大和。

Sample Input

1

4 5 2 2

3 361 649 676 588

992 762 156 993 169

662 34 638 89 543

525 165 254 809 280

Sample Output

2474

解题思路:

二位前缀和模板题
dp[i][j]为i×j的矩阵的元素和,即dp[i][j]+=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]。

在i>=x且j>=y的矩阵中找最大子矩阵,则dp[i][j]-dp[i][j-y]-dp[i-x][j]+dp[i-x][j-y]即为dp[i][j]中x×y的子矩阵的元素和。

代码如下:

Java

import java.util.Scanner;

public class HDU1559 {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int i = 0; i < T; i++) {
    
    
			int m = sc.nextInt();
			int n = sc.nextInt();
			int x = sc.nextInt();
			int y = sc.nextInt();
			int maxn = 0;
			int[][] dp = new int[m + 1][n + 1];
			for (int j = 1; j <= m; j++)
				for (int j2 = 1; j2 <= n; j2++) {
    
    
					dp[j][j2] = sc.nextInt();
					dp[j][j2] += dp[j - 1][j2] + dp[j][j2 - 1] - dp[j - 1][j2 - 1];
					if (j >= x && j2 >= y) {
    
    
						maxn = Math.max(maxn, dp[j][j2] - dp[j - x][j2] - dp[j][j2 - y] + dp[j - x][j2 - y]);
					}
				}
			System.out.println(maxn);
		}
		System.out.println();
	}
}

C++

#include<iostream>
#include<algorithm>
#include<cstdio>

using namespace std;

int dp[1010][1010];
int main(){
    
    
	int T;
	int m,n,x,y;
	cin>>T;
	while(T--){
    
    
		cin>>n>>m>>x>>y;
		int maxn = 0;
		memset(dp,0,sizeof(dp)); //初始化
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++){
    
    
				cin>>dp[i][j];
				dp[i][j] += dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];
				if(i>=x&&j>=y){
    
    
					maxn=max(maxn,dp[i][j]-dp[i][j-y]-dp[i-x][j]+dp[i-x][j-y]);
				}
			}
			cout<<maxn<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45894701/article/details/114777037