P1719 Maximum weighted rectangle (two-dimensional prefix and Java)

P1719 Maximum weighted rectangle

Topic link: https://www.luogu.com.cn/problem/P1719

Title description

In order to better prepare for NOIP2013, several girls in the computer team, LYQ, ZSC, and ZHQ, believe that we not only need a computer room, but we also need exercise, so they decided to ask the principal to apply for an after-school sports field for the computer team. I heard that they are all For the masters of the computer team, the principal did not immediately agree to them, but first gave them a math problem and told them: The area of ​​the sports field you can get is the largest number you can find.

The principal first gave them an N*N matrix. The largest weighted rectangle in the matrix is ​​required, that is, each element of the matrix has a weight, and the weight is defined on the set of integers. Find a rectangle from it. The size of the rectangle is unlimited, which is the largest sum of all the elements contained in it. Each element of the matrix belongs to [-127,127], for example

0 –2 –7 0
9 2 –6 2
-4 1 –4 1
-1 8 0 –2
in the lower left corner:

The sum of 9 2
-4 1
-1 8
is 15.

The girls were a little bit troubled, so they found HZH, who was carefully calculated by the computer team. The TZY kids helped with the calculations, but unfortunately their answers were different. We should not be vague about matters involving land. Can you help calculate the principal’s location? Is the rectangle with the largest weighted sum among the given rectangles?

Input format

The first row: n, the next is a matrix of n rows and n columns.

Output format

The sum of the largest rectangles (sub-matrices).

Sample input and output

Input #1
4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
Output #1
15
Description/Prompt
n<=120

Problem-solving ideas:

The two-digit prefix and template question
dp[i][j] is the sum of the elements of the i×j matrix, that is, dp[i][j]+=dp[i-1][j]+dp[i][j-1 ]-dp[i-1][j-1].

Find the largest sub-matrix, then dp[i][j]-dp[i][jy]-dp[ix][j]+dp[ix][jy] is x×y in dp[i][j] The sum of the elements of the sub-matrix.

code show as below:

import java.util.Scanner;

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

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/114901876
Recommended