[USACO05JAN] Muddy Fields G

\(Soution\)

把木板看成一个点,把 \(*\) 看成一条边,因为一个 \(*\) 最多对应两块木板,现在问题转化成了二分图上的最小点覆盖问题,众所周知二分图上最小点覆盖等于最大匹配

\(Code\)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2505;
int n,m,cnta,cntb,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[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 (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);
}
上一篇:分享一道我觉得有规律的题目


下一篇:VS2010编译生成lib库Release版本比Debug版本大的原因