LightOJ - 1150-Ghosts! (bfs+最大匹配+二分)

原题地址:点击打开链接

#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
struct Edge
{
	int to;
	int cost;
};
struct Point
{
	int x;
	int y;
	int step;
};
char str[26][26];
int gid[26][26];
int hid[26][26];
int vis[26][26];
int used[100];
int match[100];
int x[4]={-1,0,1,0},y[4]={0,1,0,-1};
int left,right;
vector<Edge>g[100];
void bfs(Point p,int u,int n)
{
	memset(vis,0,sizeof(vis));
	queue<Point>Q;
	Q.push(p);
	vis[p.x][p.y]=1;
	while(!Q.empty())
	{
		Point p1=Q.front();
		Q.pop();
		for(int i=0;i<4;i++)
		{
			int a=p1.x+x[i];
			int b=p1.y+y[i];
			if(a>=0&&a<n&&b>=0&&b<n&&str[a][b]!='#'&&vis[a][b]!=1)
			{
				vis[a][b]=1;
				Point pt;
				pt.x=a;
				pt.y=b;
				pt.step=p1.step+1;
				Q.push(pt);
				if(hid[a][b])
				{
					int step=pt.step*2+2;
					g[u].push_back((Edge){hid[a][b],step});
				}
			}
		}
	}
}
bool find(int u,int cost)                   //找寻增广路 
{
	for(int i=0;i<g[u].size();i++)
	{
		Edge e=g[u][i];
		if(e.cost>cost)
			continue;
		int v=e.to;
		if(!used[v])
		{
			used[v]=1;
			if(match[v]==-1||find(match[v],cost))   
			{
				match[v]=u;
				return true;
			}
		}
	}
	return false;
}
bool  max_match(int n,int cost,int m)
{
	int res=0;
	memset(match,-1,sizeof(match));
	for(int i=1;i<=n;i++)
	{
		memset(used,0,sizeof(used));
		if(find(i,cost))
			res++;
	}
	if(res==m)
		return true;
	return false;
}
int solve(int n,int m)
{
	while(left<right-1)
	{
		int mid=(left+right)/2;
		if(max_match(n,mid,m))
			right=mid;
		else
		    left=mid;
	}
	return right;
}
int main()
{
	int i,j,t,n,num1,num2,k=0;
	scanf("%d",&t);
	while(t--)
	{
		num1=num2=0;
		right=9999;left=0;
		memset(hid,0,sizeof(hid));
		memset(gid,0,sizeof(gid));
		scanf("%d",&n);
		for(i=0;i<n;i++)
			scanf("%s",str[i]);
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
			{
				if(str[i][j]=='G')
				{
					gid[i][j]=++num1;
				}
				else if(str[i][j]=='H')
				{
					hid[i][j]=++num2;
				}
			}
		for(i=1;i<=num1;i++)
			g[i].clear();
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
			{
				if(gid[i][j])
				{
					bfs((Point){i,j,0},gid[i][j],n);
				}
			}
		if(!max_match(num1,right,num2))
		{
			printf("Case %d: Vuter Dol Kupokat\n",++k);
			continue;
		}
		int res=solve(num1,num2);
		printf("Case %d: %d\n",++k,res);
	}
	return 0;
} 
/*
4
6
.....G
.H....
......
......
....H.
G.....
8
....##..
.....#..
..#...G.
G...####
H#..HG.G
#....#.#
H.#G..H.
..##...#
6
......
G.....
......
......
......
.....H
6
#.#G#.
G....#
G..##.
H###.#
...#H#
..#GHH
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值