Skip to content

Commit

Permalink
Update 850.Rectangle-Area-II_v2.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jan 11, 2022
1 parent 6fff453 commit 6b197db
Showing 1 changed file with 56 additions and 24 deletions.
80 changes: 56 additions & 24 deletions Others/850.Rectangle-Area-II/850.Rectangle-Area-II_v2.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
typedef long long ll;
using ll = long long;
class Diff2d {
public:
vector<vector<int>>f;
vector<vector<int>>diff;
int m,n;
Diff2d(int m, int n)
{
this->m = m;
this->n = n;
diff.resize(m+1);
f.resize(m+1);
for (int i=0; i<m+1; i++)
{
diff[i].resize(n+1);
f[i].resize(n+1);
}
}
void set(int x0, int y0, int x1, int y1, int val)
{
diff[x0][y0]+=val;
diff[x0][y1+1]-=val;
diff[x1+1][y0]-=val;
diff[x1+1][y1+1]+=val;
}
void compute()
{
f[0][0] = diff[0][0];
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
{
int a = i==0?0:f[i-1][j];
int b = j==0?0:f[i][j-1];
int c = (i==0||j==0)?0:f[i-1][j-1];
f[i][j] = a + b - c + diff[i][j];
}
}
};

class Solution {
ll M = 1e9+7;
public:
int rectangleArea(vector<vector<int>>& rectangles)
{
Expand All @@ -24,37 +63,30 @@ class Solution {
Y2idx[col[i]] = i;

int m = row.size(), n = col.size();
vector<vector<ll>>sum(m, vector<ll>(n));
vector<vector<ll>>diff(m, vector<ll>(n));

Diff2d grid(m,n);

for (auto rect: rectangles)
{
ll x0 = rect[0];
ll y0 = rect[1];
ll x1 = rect[2];
ll y1 = rect[3];
diff[X2idx[x0]][Y2idx[y0]]+=1;
diff[X2idx[x0]][Y2idx[y1]]-=1;
diff[X2idx[x1]][Y2idx[y0]]-=1;
diff[X2idx[x1]][Y2idx[y1]]+=1;
int i = X2idx[rect[0]];
int j = Y2idx[rect[1]];
int x = X2idx[rect[2]]-1;
int y = Y2idx[rect[3]]-1;
grid.set(i,j,x,y,1);
}

grid.compute();

ll ret = 0;
ll M = 1e9+7;
sum[0][0] = diff[0][0];
if (diff[0][0]>0)
ret += (row[1]-row[0])*(col[1]-col[0])%M;

for (int i=0; i<m-1; i++)
for (int j=0; j<n-1; j++)
{
if (i==0 && j==0) continue;
sum[i][j] = (i>=1?sum[i-1][j]:0) + (j>=1?sum[i][j-1]:0) - ((i>=1&&j>=1)?sum[i-1][j-1]:0) + diff[i][j];
if (sum[i][j] > 0)
ret = (ret + (row[i+1]-row[i])*(col[j+1]-col[j])) % M;
if (grid.f[i][j]>0)
{
ll dx = row[i+1]-row[i];
ll dy = col[j+1]-col[j];
ret += dx*dy%M;
ret %= M;
}
}

return ret;
}
};

0 comments on commit 6b197db

Please sign in to comment.