Advertisement
nikunjsoni

308

May 22nd, 2021
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. class NumMatrix {
  2. public:
  3.     int rows, cols;
  4.     vector<vector<int>> bit;
  5.     NumMatrix(vector<vector<int>>& matrix) {
  6.         rows = matrix.size();
  7.         cols = matrix[0].size();
  8.         bit.resize(rows+1, vector<int>(cols+1,  0));
  9.         buildBIT(matrix);
  10.     }
  11.    
  12.     void update(int row, int col, int val) {
  13.         int oldVal = sumRegion(row, col, row, col);
  14.         int diff = val - oldVal;
  15.         updateBIT(row+1, col+1, diff);
  16.     }
  17.    
  18.     int sumRegion(int row1, int col1, int row2, int col2) {
  19.         row1++; col1++; row2++; col2++;
  20.         return query(row2, col2)-query(row2, col1-1)-query(row1-1, col2)+query(row1-1, col1-1);
  21.     }
  22.    
  23.     void buildBIT(vector<vector<int>>& matrix){
  24.         for(int i=0; i<rows; i++)
  25.             for(int j=0; j<cols; j++)
  26.                 updateBIT(i+1, j+1, matrix[i][j]);
  27.     }
  28.    
  29.     void updateBIT(int row, int col, int val){
  30.         int tcol;
  31.         while(row <= rows){
  32.             tcol = col;
  33.             while(tcol <= cols){
  34.                 bit[row][tcol] += val;
  35.                 tcol += (tcol & -tcol);
  36.             }
  37.             row += (row & -row);
  38.         }
  39.     }
  40.    
  41.     int query(int row, int col){
  42.         int tcol, sum=0;
  43.         while(row > 0){
  44.             tcol = col;
  45.             while(tcol > 0){
  46.                 sum += bit[row][tcol];
  47.                 tcol -= (tcol & -tcol);
  48.             }
  49.             row -= (row & -row);
  50.         }
  51.         return sum;
  52.     }
  53.    
  54. };
  55.  
  56. /**
  57.  * Your NumMatrix object will be instantiated and called as such:
  58.  * NumMatrix* obj = new NumMatrix(matrix);
  59.  * obj->update(row,col,val);
  60.  * int param_2 = obj->sumRegion(row1,col1,row2,col2);
  61.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement