BZOJ2150 部落战争

BZOJ2150 部落战争

题目传送门

题解

对于每个点拆点之后,每个点都向它能够到达的点的入点连边,跑二分图最大匹配,最后所需的军队个数就是总城镇个数减去匹配个数。因为有一对点能够匹配就说明这两个城镇可以由一只军队征服,所以所需军队=总城镇个数-匹配个数。

code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool Finish_read;
template<class T>inline void read(T &x){Finish_read=0;x=0;int f=1;char ch=getchar();while(!isdigit(ch)){if(ch=='-')f=-1;if(ch==EOF)return;ch=getchar();}while(isdigit(ch))x=x*10+ch-'0',ch=getchar();x*=f;Finish_read=1;}
template<class T>inline void print(T x){if(x/10!=0)print(x/10);putchar(x%10+'0');}
template<class T>inline void writeln(T x){if(x<0)putchar('-');x=abs(x);print(x);putchar('\n');}
template<class T>inline void write(T x){if(x<0)putchar('-');x=abs(x);print(x);}
/*================Header Template==============*/
#define PAUSE printf("Press Enter key to continue..."); fgetc(stdin);
const int maxn=55;
int n,m,r,c,tot;
char s[maxn];
int mp[maxn][maxn],head[100005];
int belong[100005],vis[100005];
struct edge {
	int to,nxt;
}E[500005];
/*==================Define Area================*/
bool judge(int x,int y) {
	if(mp[x][y]||x<1||x>n||y<1||y>m) return 0;
	else return 1;
}

void addedge(int u,int v) {
	E[++tot].to=v;E[tot].nxt=head[u];head[u]=tot;
	E[++tot].to=u;E[tot].nxt=head[v];head[v]=tot;
}

int turn(int x,int y) {
	return (x-1)*m+y;
}

bool Solve(int x) {
	for(int i=head[x];~i;i=E[i].nxt) {
		int to=E[i].to;
		if(vis[to]) continue;
		vis[to]=1;
		if(!belong[to]||Solve(belong[to])) return belong[to]=x;
	}
	return 0;
}

int main() {
	memset(head,-1,sizeof head);
	read(n);read(m);read(r);read(c);
	int cnt=0;
	for(int i=1;i<=n;i++) {
		scanf("%s",s);
		for(int j=0;j<m;j++) {
			mp[i][j+1]=(s[j]=='x');
			cnt+=(s[j]=='.');
		}
	}
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			if(mp[i][j]) continue ;
			int x=turn(i,j),y;
			int nx=i+r,ny=j+c;
			if(judge(nx,ny)) {
				y=turn(nx,ny);
				addedge(x,y+n*m);
			}
			nx=i+r,ny=j-c;
			if(judge(nx,ny)) {
				y=turn(nx,ny);
				addedge(x,y+n*m);
			}
			nx=i+c,ny=j+r;
			if(judge(nx,ny)) {
				y=turn(nx,ny);
				addedge(x,y+n*m);
			}
			nx=i+c,ny=j-r;
			if(judge(nx,ny)) {
				y=turn(nx,ny);
				addedge(x,y+n*m);
			}
		}
	}
	int ans=0;
	for(int i=1;i<=n*m;i++) {
		memset(vis,0,sizeof vis);
		ans+=Solve(i);
	}
	printf("%d\n",cnt-ans);
	return 0;
}
posted @ 2018-08-06 21:33  Apocrypha  阅读(190)  评论(0编辑  收藏  举报