因为这道题有网络流标签,所以很自然的想到网络流。
然后发现最大流好像不太好刻画,于是使用最小割。
首先算出所有的相邻格子的对数,然后减去相邻的相同颜色格子的对数。
但是这里有个问题:如果直接求最小割,求到的是不同颜色的最小对数,而非相同颜色的最小对数,于是可以考虑黑白染色,把黑(白的也可以)的所有格子翻转颜色,再求最小割就相当于原来相同颜色格子的最小对数。
连边:
设将 集合内的点染成白色,把 集合内的点染成白色(当然你也可以反过来做)。
如果当前格子确定是白色,则从 到当前格子连一条 的边,表示该边不能被割掉(即它一定在 集合里),实现时 其实就够了。
如果当前格子确定是黑色,同理可得。
如果是问号代表没有限制,就啥也不用连。
然后向上下左右各连一条边权为 的边表示如果颜色不同那么变换后的网格的总不同颜色对数多 (即原来网格的相同颜色对数多 ),就做完了。
当然,这道题有道 双倍经验。
有一点点不一样,具体可以看我写的 题解。
#include <bits/stdc++.h>
using namespace std;
const int N = 100 + 10, V = 1e4 + 10, E = 1e5 + 10;
int n, tot, S, T, id[N][N], dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
char g[N][N];
template<typename T>
struct FlowGraph{ // Max Flow Graph
int s, t, vtot;
int h[V], etot;
int dist[V], cur[V];
struct Edge{
int v, nxt;
T f;
}e[E << 1];
void add_edge(int u, int v, T f, T f2 = 0) {
e[etot] = {v, h[u], f}; h[u] = etot ++;
e[etot] = {u, h[v], f2}; h[v] = etot ++;
}
bool bfs() {
for(int i = 1; i <= vtot; i ++) {
dist[i] = 0;
cur[i] = h[i];
}
queue<int> q;
q.push(s); dist[s] = 1;
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i = h[u]; ~i; i = e[i].nxt) {
int v = e[i].v;
if(e[i].f && !dist[v]) {
dist[v] = dist[u] + 1;
if(v == t) return true;
q.push(v);
}
}
}
return false;
}
T dfs(int u, T m) {
if(u == t) return m;
T flow = 0;
for(int &i = cur[u]; ~i; i = e[i].nxt) {
int v = e[i].v;
if(e[i].f && dist[v] == dist[u] + 1) {
T f = dfs(v, min(e[i].f, m));
e[i].f -= f;
e[i ^ 1].f += f;
flow += f;
if(!(m -= f)) break;
}
}
if(!flow) dist[u] = -1;
return flow;
}
T dinic() {
T flow = 0;
while(bfs()) flow += dfs(s, numeric_limits<T>::max());
return flow;
}
void init(int s_, int t_, int vtot_) {
s = s_, t = t_, vtot = vtot_, etot = 0;
for(int i = 1; i <= vtot; i ++) h[i] = -1;
}
};
FlowGraph<int> G;
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i ++) {
scanf("%s", g[i]);
for(int j = 0; j < n; j ++) {
id[i][j] = ++ tot;
if(((i + j) & 1) && g[i][j] != '?') g[i][j] ^= 'B' ^ 'W';
}
}
S = ++ tot, T = ++ tot;
G.init(S, T, T);
for(int i = 0; i < n; i ++) {
for(int j = 0; j < n; j ++) {
if(g[i][j] == 'B') G.add_edge(S, id[i][j], 4);
if(g[i][j] == 'W') G.add_edge(id[i][j], T, 4);
for(int k = 0; k < 4; k ++) {
int x = i + dx[k], y = j + dy[k];
if(x >= 0 && x < n && y >= 0 && y < n) G.add_edge(id[i][j], id[x][y], 1);
}
}
}
printf("%d\n", 2 * n * (n - 1) - G.dinic());
return 0;
}