相邻点连边,跑二分图匹配,匹配上一对就可以少用一个圈,答案就是总数-匹配数(由于对称匹配,匹配数要除2)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
void ____(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); }
const int MAXN = 444;
const int dir[2][2] = {{1,0},{0,1}};
char gp[MAXN][MAXN];
int n,m,match[MAXN],vis[MAXN];
vector<int> G[MAXN];
bool dfs(int u){
vis[u] = true;
for(int i = 0; i < (int)G[u].size(); i++){
int v = G[u][i];
if(match[v]==-1||(!vis[match[v]]&&dfs(match[v]))){
match[v] = u;
return true;
}
}
return false;
}
int hungary(){
int tot = 0;
memset(match,255,sizeof(match));
for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++){
if(gp[i][j]=='o') continue;
memset(vis,0,sizeof(vis));
if(dfs((i-1)*m+j)) tot++;
}
return tot;
}
void solve(){
scanf("%d %d",&n,&m);
for(int i = 1; i <= n * m; i++) G[i].clear();
for(int i = 1; i <= n; i++) scanf("%s",gp[i]+1);
int tot = 0;
for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++){
if(gp[i][j]=='o') continue;
tot++;
for(int d = 0; d < 2; d++){
int nx = i + dir[d][0];
int ny = j + dir[d][1];
if(nx<1||nx>n||ny<1||ny>m||gp[nx][ny]!='*') continue;
G[(i-1)*m+j].push_back((nx-1)*m+ny);
G[(nx-1)*m+ny].push_back((i-1)*m+j);
}
}
printf("%d\n",tot-hungary()/2);
}
int main(){
int T;
for(scanf("%d",&T); T; T--) solve();
return 0;
}