A template for an artwork is a white grid of n × m squares. The artwork will be created by painting q horizontal and vertical black strokes. A stroke starts from square (x 1 , y 1 ), ends at square (x 2 , y 2 ) (x 1 = x 2 or y 1 = y 2 ) and changes the color of all squares (x, y) to black where
x 1 ≤ x ≤ x 2 and y 1 ≤ y ≤ y 2 .
The beauty of an artwork is the number of regions in the grid. Each region consists of one or more white squares that are connected to each other using a path of white squares in the grid, walking horizontally or vertically but not diagonally. The initial beauty of the artwork is 1. Your task is to calculate the beauty after each new stroke. Figure A.1 illustrates how the beauty of the artwork varies in Sample Input 1.
The ?rst line of input contains three integers n, m and q (1 ≤ n, m ≤ 1000, 1 ≤ q ≤ 104 ).
Then follow q lines that describe the strokes. Each line consists of four integers x 1 , y 1 , x 2 and y 2 (1 ≤ x 1 ≤ x 2 ≤ n, 1 ≤ y 1 ≤ y 2 ≤ m). Either x 1 = x 2 or y 1 = y 2 (or both).
For each of the q strokes, output a line containing the beauty of the artwork after the stroke.
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e3+10;
const int dx[]={1,-1,0,0};
const int dy[]={0,0,1,-1};
int n,m,q,cnt;
struct line{
int x1,x2,y1,y2;}li[N*10];
int f[N*N],num[N][N],ans[N*10];
int Hash(int x,int y)
{
return (x-1)*m+y;
}
int fund(int x)
{
if (f[x]==x) return f[x];
return f[x]=fund(f[x]);
}
void join(int x,int y)
{
int fx=fund(x),fy=fund(y);
if (fx!=fy)
{
cnt--;
f[fx]=fy;
}
}
void dfs(int x,int y)
{
int id=Hash(x,y);
for (int i=0;i<4;i++)
{
int fx=x+dx[i],fy=y+dy[i];
if (fx<1||fx>n||fy<1||fy>m) continue;
if (num[fx][fy]==0)
{
join(id,Hash(fx,fy));
}
}
}
void print(line l)
{
for (int i=l.x1;i<=l.x2;i++)
for (int j=l.y1;j<=l.y2;j++)
{
if (num[i][j]==0) cnt--;
num[i][j]++;
}
}
void reprint(line l)
{
for (int i=l.x1;i<=l.x2;i++)
for (int j=l.y1;j<=l.y2;j++)
{
num[i][j]--;
if (num[i][j]==0)
{
cnt++;
dfs(i,j);
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&q);
cnt=n*m;
for (int i=1;i<=cnt;i++) f[i]=i;
for (int i=1;i<=q;i++)
{
scanf("%d%d%d%d",&li[i].x1,&li[i].y1,&li[i].x2,&li[i].y2);
print(li[i]);
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if (num[i][j]==0) dfs(i,j);
for (int i=q;i>=1;i--)
{
ans[i]=cnt;
reprint(li[i]);
}
for (int i=1;i<=q;i++) printf("%d\n",ans[i]);
return 0;
}
View Code