这是一道好题,按行建线段树,每个点维护上下边界的连通性,详细见代码注释

网上写法不一,自认为比较简单,就放出来相出来献丑吧

 var u,d:array[..,..] of longint;  //u[]上边界,d[]下边界
s,fa,q:array[..] of longint;
c:array[..,..] of longint; //维护对应颜色块数
a:array[..,..] of longint;
j,i,n,m,x,y:longint; function getf(x:longint):longint;
begin
if fa[x]<>x then fa[x]:=getf(fa[x]);
exit(fa[x]);
end; procedure union(i,m:longint);
var j,k1,k2,t:longint;
begin
c[i,]:=c[i*,]+c[i*+,];
c[i,]:=c[i*,]+c[i*+,];
for j:= to n do
begin
fa[j]:=u[i*,j];
fa[j+n]:=d[i*,j];
fa[j+*n]:=u[i*+,j]+*n; //防止编号重复
fa[j+*n]:=d[i*+,j]+*n;
end;
for j:= to n do
if a[m+,j]=a[m,j] then //子区间相邻连通块合并
begin
k1:=getf(fa[j+n]);
k2:=getf(fa[j+*n]);
if k1<>k2 then
begin
fa[k2]:=k1;
dec(c[i,a[m,j]]);
end;
end;
t:=;
for j:= to n do
begin
k1:=getf(fa[j]); //对整个区间上边界连通性重新标号
if s[k1]= then
begin
inc(t);
q[t]:=k1;
s[k1]:=j;
end;
u[i,j]:=s[k1];
k2:=getf(fa[j+*n]); //对整个区间下边界连通性重新标号
if s[k2]= then
begin
inc(t);
q[t]:=k2;
s[k2]:=j+n; //防止编号重复,上边界编号1~n,下边界编号n+~2n
end;
d[i,j]:=s[k2];
end;
for j:= to t do
s[q[j]]:=;
end; procedure leaf(i,row:longint);
var j,t:longint;
begin
t:=;
c[i,]:=; c[i,]:=;
for j:= to n do
if (j<>) and (a[row,j]=a[row,j-]) then
begin
u[i,j]:=u[i,j-];
d[i,j]:=d[i,j-];
end
else begin
inc(c[i,a[row,j]]);
u[i,j]:=j; d[i,j]:=j; //连通块以起始位置为编号,这样比较方便
end;
end; procedure build(i,l,r:longint);
var m:longint;
begin
if l=r then leaf(i,l)
else begin
m:=(l+r) shr ;
build(i*,l,m);
build(i*+,m+,r);
union(i,m);
end;
end; procedure work(i,l,r:longint);
var m:longint;
begin
if l=r then leaf(i,l)
else begin
m:=(l+r) shr ;
if x<=m then work(i*,l,m)
else work(i*+,m+,r);
union(i,m);
end;
end; begin
readln(n);
for i:= to n do
for j:= to n do
read(a[i,j]);
build(,,n);
readln(m);
for i:= to m do
begin
readln(x,y);
a[x,y]:=-a[x,y];
work(,,n);
writeln(c[,],' ',c[,]);
end;
end.
05-11 18:31