G - To the Max POJ - 1050

4373 ワード

Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. As an example, the maximal sub-rectangle of the array:
0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2 is in the lower left corner:
9 2 -4 1 -1 8 and has a sum of 15. Input The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127]. Output Output the sum of the maximal sub-rectangle. Sample Input 4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1
8 0 -2 Sample Output 15
最大サブマトリクスと問題は、連続行の最大サブセグメント和、すなわち最大フィールド和に相当するアップグレード版に変換できますが、実際にはダイナミックプランニングも必ずすべての可能性を考慮していますが、いくつかのサブ問題の解答を保存するだけで、実はこの最大サブマトリクスと問題だと思います.動的に計画されているが実際には以前のサブ問題の解答は用いられておらず,サブマトリクスは必ず連続行連続列で構成されていることが想像でき,異なる連続行が異なる連続列で得られる最大和に簡略化できる.この話は少し迂回しているかもしれませんが、以下の行列を見ることができます.a 11 a 12 a 13 a 14 a 21 a 22 a 23 a 31 a 31 a 32 a 33 a 34 a 41 a 42 a 43 a 44もし私たちが2*nの行列を取るならば、明らかに、連続する2行はn-1の選択があって、この列も連続していることを見ることができて、例えば、私たちはn=1を取って、そして第2の第3行から選択して、それでは1列を取るならばnの選択があって、しかも中から最大の和を見つけて、それからn=2の時、またn-1の選択があり、列数を増やすときに、選択した各行の列を加えなければならないという問題に気づくことができます.さらに、列数を増やす以上、各行の列の数を加えなければならないので、状態を直接圧縮して、選択したi行を1行に圧縮することができます.次に、この行で最大フィールドとを求めます.コードは次のとおりです.
#include 
#include 
#include 
#include 
#include 
#define INF 0x3f3f3f3f
int a[105][105];
int main()
{
    int N;
    while (scanf("%d", &N) != EOF) {
        int x;
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                scanf("%d", &x);
                a[i][j] = a[i - 1][j] + x;
            }
        }
        int MAX = -INF;
        for (int i = 0; i <= N; ++i) {//                  
            for (int j = i + 1; j <= N; ++j) {
                int sum = 0;
                for (int k = 1; k <= N; ++k) {
                    sum = sum + a[j][k] - a[i][k];
                    MAX = std::max(sum, MAX);
                    if (sum < 0)
                        sum = 0;
                }
            }
        }
        printf("%d
"
, MAX); } return 0; }