[HEOI2016/TJOI2016]游戏

\(Solution\)

如何去确定以个炸弹,可以用一行和一列\(i,j\),那么就相当于行和列进行最匹配,对于一个#能把行分成两部分,处理每行每列的每部分,如果交点不是x那就可以匹配

总结:\(dinic\)一般时间复杂度为\(O(nm)\),跑二分图匹配为\(O(m\sqrt{n})\)

\(Code\)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2505;
int n,m,cnta,cntb,vis[55][55],tot = 1,h[N << 1],dep[N << 1],q[N << 1],cur[N << 1],S,T;
char s[55][55];

struct nd{
	int l,r,id;
}a[N],b[N];
struct edge{
	int to,nxt,z;
}e[N * N];
void add(int x,int y,int z)
{
	e[++tot] = edge{y,h[x],z},h[x] = tot;
	e[++tot] = edge{x,h[y],0},h[y] = tot;
}
int bfs()
{
	for (int i = 1; i <= T; i++) cur[i] = h[i];
	memset(dep,0,sizeof dep);
	int head = 0,tail = 1;
	q[1] = S,dep[S] = 1;
	while (head < tail)
	{
		int u = q[++head];
		for (int i = h[u]; i; i = e[i].nxt)
		{
			int v = e[i].to;
			if (dep[v] || e[i].z <= 0) continue;
			dep[v] = dep[u] + 1,q[++tail] = v;
		}
	}
	return dep[T];
}
int dinic(int u,int mn,int fa)
{
	if (u == T || mn <= 0) return mn;
	int sum = 0,flow = 0;
	for (int &i = cur[u]; i; i = e[i].nxt)
	{
		int v = e[i].to;
		if (v == fa || dep[v] != dep[u] + 1 || e[i].z <= 0) continue;
		sum = dinic(v,min(mn,e[i].z),u);
		if (sum <= 0) continue;
		flow += sum,mn -= sum,e[i].z -= sum,e[i ^ 1].z += sum;
		if (mn <= 0) continue;
	}
	return flow;
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i = 1; i <= n; i++)
	{
		scanf("%s",s[i] + 1);
		if (s[i][1] != '#') a[++cnta] = nd{1,1,i};
		for (int j = 2; j <= m; j++)
		{
			if (s[i][j - 1] == '#' && s[i][j] != '#') a[++cnta] = nd{j,j,i};
			if (s[i][j] != '#') a[cnta].r = j;
		}
		for (int j = 1; j <= m; j++) 
			if (s[i][j] == 'x') vis[i][j] = 1;
	}
	for (int j = 1; j <= m; j++)
	{
		if (s[1][j] != '#') b[++cntb] = nd{1,1,j};
		for (int i = 2; i <= n; i++)
		{
			if (s[i - 1][j] == '#' && s[i][j] != '#') b[++cntb] = nd{i,i,j};
			if (s[i][j] != '#') b[cntb].r = i;
		}
	}
	S = cnta + cntb + 1,T = S + 1;
	for (int i = 1; i <= cnta; i++) add(S,i,1);
	for (int i = 1; i <= cntb; i++) add(i + cnta,T,1);
	for (int i = 1; i <= cnta; i++)
		for (int j = 1; j <= cntb; j++)
		{
			if (b[j].id > a[i].r || b[j].id < a[i].l) continue;
			if (vis[a[i].id][b[j].id]) continue;
			if (a[i].id > b[j].r || a[i].id < b[j].l) continue;
			add(i,j + cnta,1);
		}
	int ans = 0;
	while (bfs()) ans += dinic(S,2147483647,S);
	printf("%d\n",ans);
}
posted @ 2022-01-23 11:54  RiverSheep  阅读(23)  评论(0编辑  收藏  举报