AT_abc193_f Zebraness

· · 题解

太好了,直接来抢一波题解首杀。

看上去没有什么很直观的解法,于是考虑网络流。

我们来修改一下题目条件。如果这个题是“相邻两个同色格子贡献为 1”,就可以套用一个很典的最小割模型:P4313 文理分科。

为了防止有些同学不知道,还是讲一下这个模型:

把每个格子看作点,划分到 S 集合表示白色,划分到 T 集合表示黑色。

对于每对相邻格子 X,Y,新建两个虚点 A,B,连边如下:

这里,保留 S 到 A 的边代表 X,Y 都为白色,产生 1 贡献;保留 B 到 T 的边代表 X,Y 都为黑色,产生 1 贡献。

为什么呢?假如保留 S 到 A 的边,而 X,Y 中某个点选了黑色,由于 inf 边不能被割,此时 S,T 一定联通,不满足条件。因此,这条边保留当且仅当 X,Y 都选白色。B 也是同理。

此时的答案就是“边权为 1 的边数-最小割”。

然后你会说:就这,你把题目条件都改了,然后做出来了,好棒棒哦。

嗯你说的不无道理,如果按原题条件来做的话,上面的模型就失效了,你无法保证两个格子异色时产生贡献 1。

这个问题很好解决:我们令所有“行编号+列编号为奇数”的格子反色,比如 s[1][2]=B,就改成 s[1][2]=W,而 s[2][2] 的颜色不改变。这样就转化成之前那个可以解决的问题了。由于贡献只和相邻格子颜色有关,是不会产生什么额外影响的。

做完啦,上 Code

#include<bits/stdc++.h>
#define p(x,y) (((x)-1)*n+(y))
using namespace std;
const int maxn=5e4,inf=0x3f3f3f3f;
int n,tot,N;
char s[103][103];
namespace Edge{
    int head[maxn+5],flag=1;
    struct star{int to,nxt,val;}edge[3000005];
    inline void add(int u,int v,int val){
        edge[++flag]=(star){v,head[u],val},head[u]=flag;
    }
    inline void exadd(int u,int v,int val){add(u,v,val),add(v,u,0);}
}using namespace Edge;
namespace min_cut{
    const int S=0,T=maxn+1;
    int depth[maxn+5],now[maxn+5];
    inline bool bfs(){
        memcpy(now,head,sizeof(now));
        memset(depth,0,sizeof(depth));
        queue<int>q;
        q.emplace(S),depth[S]=1;
        while(q.size()){
            int h=q.front();q.pop();
            for(int i=head[h];i;i=edge[i].nxt){
                int v=edge[i].to;
                if(depth[v]||!edge[i].val)continue;
                depth[v]=depth[h]+1,q.emplace(v);
                if(v==T)return 1;
            }
        }return 0;
    }
    int dfs(int id,int flow){
        if(id==T||!flow)return flow;
        int tot=0;
        for(int &i=now[id];i;i=edge[i].nxt){
            int v=edge[i].to;
            if(depth[v]!=depth[id]+1||!edge[i].val)continue;
            int res=dfs(v,min(flow,edge[i].val));
            edge[i].val-=res,edge[i^1].val+=res;
            tot+=res,flow-=res;
        }return tot;
    }
    inline int Dinic(){
        int res=0;
        while(bfs())res+=dfs(S,inf);
        return res;
    }
}using namespace min_cut;
int main(){
    scanf("%d",&n),N=p(n,n);
    for(int i=1;i<=n;i++)scanf("%s",s[i]+1);
    for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++){
        if(s[i][j]=='B')((i+j)&1)?exadd(S,p(i,j),inf):exadd(p(i,j),T,inf);
        if(s[i][j]=='W')((i+j)&1)?exadd(p(i,j),T,inf):exadd(S,p(i,j),inf);
        if(i<n){
            ++N,exadd(S,N,1);
            exadd(N,p(i,j),inf),exadd(N,p(i+1,j),inf);
            ++N,exadd(N,T,1);
            exadd(p(i,j),N,inf),exadd(p(i+1,j),N,inf);
        }
        if(j<n){
            ++N,exadd(S,N,1);
            exadd(N,p(i,j),inf),exadd(N,p(i,j+1),inf);
            ++N,exadd(N,T,1);
            exadd(p(i,j),N,inf),exadd(p(i,j+1),N,inf);
        }
    }printf("%d",N-p(n,n)-Dinic());return 0;
}