Two-dimensional prefix and template (DP, tolerance and exclusion principle)

The idea of ​​using DP and the principle of tolerance and exclusion.

  • s [ i ] [ j ] s[i][j] s [ i ] [ j ] record from[1] [1] [1][1][ 1 ] [ 1 ] arrival[i] [j] [i[ i ] [ j ] The sum of the rectangular areas formed.
  • 状态更新: s [ i ] [ j ] = s [ i − 1 ] [ j ] + s [ i ] [ j − 1 ] − s [ i − 1 ] [ j − 1 + g [ i ] [ j ] s[i][j] =s[i-1][j]+s[i][j-1]-s[i-1][j-1+g[i][j] s[i][j]=s[i1][j]+s[i][j1]s[i1][j1+g [ i ] [ j ] The subscript starts from 1
  • Find [x 1] [y 1] [x1][y1][ x 1 ] [ y 1 ] to[x 2] [y 2] [x2][y2][ x 2 ] [ y 2 ] and the rectangular area formed by:
    area = s [x 2] [y 2] − s [x 1 − 1] [y 2] − s [x 2] [y 1 − 1] + s [x 1 − 1] [y 1 − 1] area = s[x2][y2]-s[x1-1][y2]-s[x2][y1-1]+s[x1-1] [y1-1]area=s[x2][y2]s[x11 ] [ y 2 ]s[x2][y11]+s[x11][y11]
class NumMatrix {
    
    
    vector<vector<int>> s; 
    int m = 0 , n = 0;
public:
    NumMatrix(vector<vector<int>>& g) {
    
    
        m = g.size()a
        if(m) n = g[0].size();
        if(n==0) return;
        s.resize(m+1,vector<int>(n+1,0)); 
        for(int i=1;i<=m;i++){
    
    
            for(int j=1;j<=n;j++){
    
    
                s[i][j] = s[i-1][j]+s[i][j-1]-s[i-1][j-1]+g[i-1][j-1];
            }
        }
    }
    
    int sumRegion(int x1, int y1, int x2, int y2) {
    
    
        if(n==0) return 0;
        x1++, y1++, x2++, y2++; // 下标从1开始
        return s[x2][y2]-s[x1-1][y2]-s[x2][y1-1]+s[x1-1][y1-1];
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */

Template questions: 304. Two-dimensional area and retrieval-matrix is ​​immutable

Guess you like

Origin blog.csdn.net/qq_44846324/article/details/108376898