POJ 2112 Optimal Milking, 二分, floyd, 二分图

http://poj.org/problem?id=2112

 

Optimal Milking

TimeLimit: 2000MS           MemoryLimit: 30000K

Case TimeLimit: 1000MS



题目大意:

现在有K个机器,C头牛,每头牛要使用一个机器,每个机器最多被M头牛使用。

机器标号为1~K,牛标号为K+1~K+C,用矩阵给出这K+C个结点之间各条边的距离。

现在要使每头牛有一台机器用,问所有牛要走的最长一条边的最短距离是多少。

 

Input

* Line 1: A single line withthree space-separated integers: K, C, and M. 

* Lines 2.. ...: Each of these K+C lines of K+C space-separated integersdescribes the distances between pairs of various entities. The input forms asymmetric matrix. Line 2 tells the distances from milking machine 1 to each ofthe other entities; line 3 tells the distances from machine 2 to each of theother entities, and so on. Distances of entities directly connected by a pathare positive integers no larger than 200. Entities not directly connected by apath have a distance of 0. ...(后面的废话省略)

Output

A single line with a singleinteger that is the minimum possible total distance for the furthest walkingcow. 

Sample Input

2 3 2

0 3 2 1 1

3 0 3 2 0

2 3 0 1 0

1 2 1 0 2

1 0 0 2 0

Sample Output

2

Source

USACO2003 U S Open

 

 

 

解法:

问最大的最小值,显然要二分答案。

先用floyd求最短路;再二分答案,用二分结果来建立二分图;然后用裸的增广路来检验这个二分图能否满足匹配要求即可。

建二分图时,将每个机器分成M个结点,即可化成一般的二分图。

 

596K 297MS

 

<span style="font-size:18px;">/*
floyd,二分答案,二分图匹配。简洁明了 
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int inf=250,Max=0x3f3f3f3f;

int dis[inf][inf];

//二分图匹配:
bool map[30*15+10][inf];//将每个机器拆成m个点存储。map[i][j]表示第i个机器到第j头牛之间的边 
bool vis[30*15+10];
int use[30*15+10];

int k,c,m,n;


void floyd(){
	for (int r=1;r<=n;r++)
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++)
				dis[i][j]=min(dis[i][j],dis[i][r]+dis[r][j]);	
}

void buildmap(int maxd){		//建二分图 
	memset(map,false,sizeof(map));
	
	for (int i=1;i<=k;i++)
		for (int j=k+1;j<=n;j++)
			if (dis[i][j]<=maxd)
				for (int r=0;r<m;r++)	//把每个机器拆成m个 
					map[r*k+i][j-k]=true;
}

bool dfs(int i){
	for (int j=1;j<=k*m;j++){
		if (map[j][i] && !vis[j]){
			vis[j]=true;
			if (!use[j] || dfs(use[j])){
				use[j]=i;
				return true;
			}
		}
	}
	return false;
}
bool match(){		//增广路求二分图匹配 
	memset(use,0,sizeof(use));
	for (int i=1;i<=c;i++){
		memset(vis,false,sizeof(vis));
		if (!dfs(i)) return false;		//只要有一个点不能匹配就算建图失败 
	}
	return true;
}


int main(){
	cin>>k>>c>>m;	n=k+c;
	for (int i=1;i<=n;i++) for (int j=1;j<=n;j++){
		scanf("%d",&dis[i][j]);
		if (!dis[i][j]) dis[i][j]=Max;
	}
		
	
	floyd();
	
	//二分答案 
	int l=0,r=200*n,ans;
	while(l<=r){
		int mid=(l+r)>>1;
		buildmap(mid);			//建二分图:二分图中只保留长度小于等于mid的边 
		if (match()) r=mid-1,ans=mid;		//能够匹配说明:最长边的最小值不够小 
		else l=mid+1;
	}
	
	cout<<ans;
	return 0;
} </span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值