ZOJ 1002 Fire Net (搜索 || 二分图)

15 篇文章 0 订阅
7 篇文章 0 订阅

可以把一行分成多行,一列分出多列,然后用行和列坐标之间建二分图,求最大匹配.

#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
const int maxn = 40;
char grid[5][5];
bool g[maxn][maxn], vis[maxn];
int rg[5][5], cg[5][5], fa[maxn], n, m;

bool dfs(int u){
	for (int v = 1; v <= m; ++v){
		if(g[u][v] && !vis[v]){
			vis[v] = 1;
			if(fa[v] == 0 || dfs(fa[v])){
				fa[v] = u;
				return true;
			}
		}
	}
	return false;
}
int hungary(){
	int ans = 0;
	memset(fa, 0, sizeof(fa));
	for (int i = 1; i <= n; ++i){
		memset(vis, 0, sizeof(vis));
		if(dfs(i))ans++;
	}
	return ans;
}
int main(){
	while (scanf("%d\n", &n) && n){
		memset(g, 0, sizeof(g));
		memset(rg, 0, sizeof(rg));
		memset(cg, 0, sizeof(cg));
		for (int i = 0; i < n; ++i){
			gets(grid[i]);
		}
		int r = 1;
		for (int i = 0; i < n; ++i){
			for (int j = 0; j < n; ++j){
				if(grid[i][j] == 'X'){
					r++;
				}else{
					rg[i][j] = r;
				}
			}
			++r;
		}
		int c = r + 1;
		for (int i = 0; i < n; ++i){
			for (int j = 0; j < n; ++j){
				if(grid[j][i] == 'X'){
					c++;
				}else{
					cg[j][i] = c;
				}
			}
			++c;
		}
		for (int i = 0; i < n; ++i){
			for (int j = 0; j < n; ++j){
				if(grid[i][j] == '.'){
					g[rg[i][j]][cg[i][j]] = g[cg[i][j]][rg[i][j]] = 1;
				}
			}
		}
		n = r, m = c;
		printf("%d\n",hungary());
	}
	return 0;
}

搜索的做法:

#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
const int maxn = 5;
char grid[maxn][maxn];
bool vis[maxn][maxn];
int  di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1}, n, ans;
bool canput(int ci, int cj){
	for (int i = 0; i < 4; ++i){
		for (int ti = ci, tj =cj; ti >= 0 && ti < n && tj >= 0 && tj < n && grid[ti][tj] == '.'; ti += di[i], tj += dj[i]){
			if(vis[ti][tj])return false;
		}
	}
	return true;
}
void dfs(int cp, int cnt){
	if(cnt > ans){
		ans = cnt;
	}
	if(cp >= n * n)return;
	int ci = cp / n, cj = cp %n;
	if(grid[ci][cj] == '.' && canput(ci, cj)){
		vis[ci][cj] = 1;
		dfs(cp + 1, cnt + 1);
		vis[ci][cj] = 0;
	}
	dfs(cp + 1, cnt);
}
int main(){
	while (scanf("%d\n", &n) && n){
		for (int i = 0; i < n; ++i){
			gets(grid[i]);
		}
		ans = 0;
		memset(vis, 0, sizeof(vis));
		dfs(0, 0);
		printf("%d\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值