zoukankan      html  css  js  c++  java
  • 最大的和

     

     

     解析转载自https://www.acwing.com/solution/content/4127/

    =====转载开始=====

    左上角和右下角两个点可以确定一个矩形。枚举这两个点要用4个for循环 如果用二维前缀和,那么这个做法的复杂度的就是O(n^4)。

    其实这个方案可以优化,那就是不枚举点。

     

    所以我们可以利用前缀和数组表示出每个色块表示的值,然后做类似找一维数组最大连续和的操作。这样来枚举出最优矩形。

    枚举边界要用3个for,复杂度为 O(n^3)

    =====转载结束=====

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 const int N = 110;
     4 int a[N][N];
     5 int main() {
     6     int n;
     7     cin >> n;
     8     for (int i = 1; i <= n; i++) {
     9         for (int j = 1; j <= n; j++) {
    10             cin >> a[i][j];
    11             a[i][j] += a[i - 1][j]; //同一列的前缀和
    12         }
    13     }
    14     int res = -2e9;
    15     for (int i = 1; i <= n; i++) { //枚举边界1
    16         for (int j = i; j <= n; j++) { //枚举边界2
    17             int last = 0;
    18             for (int k = 1; k <= n; k++) { //枚举边界
    19                 //last是前面数字的最大和如果小于0 舍弃
    20                 last = max(last, 0) + a[j][k] - a[i - 1][k]; 
    21                 res = max(res, last);
    22             }
    23         }
    24     }
    25     cout << res << endl;
    26     return 0;
    27 }
  • 相关阅读:
    HDU-5818-Joint Stacks
    蓝桥杯-2016CC-卡片换位
    HDU-2255-奔小康赚大钱(KM算法)
    蓝桥杯-PREV31-小朋友排队
    crypto.js加密传输
    js之对象
    LigerUi之ligerMenu 右键菜单
    关于js中window.location.href,location.href,parent.location.href,top.location.href的用法
    设置js的ctx
    AngularJS简单例子
  • 原文地址:https://www.cnblogs.com/fx1998/p/14033056.html
Copyright © 2011-2022 走看看