欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

N - Optimal Milking POJ - 2112(二分 + Floyd + 二分图多重匹配)

程序员文章站 2022-03-07 20:55:57
题目链接解题思路:先算出每头奶牛到每块挤奶地的最短距离,如果不存在则为inf二分最长距离,并以此建边,进行多重匹配AC代码:// Test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。////二分答案 + 二分图多重匹配 #include #include #include #include #include

题目链接
解题思路:

  • 先算出每头奶牛到每块挤奶地的最短距离,如果不存在则为inf
  • 二分最长距离,并以此建边,进行多重匹配

AC代码:

// Test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
//二分答案 + 二分图多重匹配 
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int maxn = 510;
int K, C, M, mmax;
int dis[maxn][maxn], graph[maxn][maxn], match[maxn][maxn], vis[maxn];
void Floyd() {
	for (int k = 1; k <= K + C; k++)
		for (int i = 1; i <= K + C; i++)
			for (int j = 1; j <= K + C; j++)
				if (i != j && dis[i][j] > dis[i][k] + dis[k][j])
					dis[i][j] = dis[i][k] + dis[k][j];
	for (int i = 1; i <= K + C; i++)
		for (int j = 1; j <= K + C; j++)
			mmax = max(dis[i][j], mmax);
}
void Init() {
	memset(dis, 0x3f, sizeof(dis));
	int x;
	for (int i = 1; i <= K + C; i++)
		for (int j = 1; j <= K + C; j++) {
			cin >> x;
			if (x) dis[i][j] = x;
		}
	Floyd();
}
void Build_graph(int mid) {
	for (int i = K + 1; i <= K + C; i++)
		for (int j = 1; j <= K; j++)
			if (dis[i][j] <= mid) graph[i][j] = 1;
			else graph[i][j] = 0;
}
bool dfs(int x, int mid) {
	for (int i = 1; i <= K; i++) {
		if (graph[x][i] && !vis[i]) {
			vis[i] = 1;
			if (match[i][0] < M) {
				match[i][++match[i][0]] = x;
				return true;
			}
			for (int j = 1; j <= match[i][0]; j++)
				if (dfs(match[i][j], mid)) {
					match[i][j] = x;
					return true;
				}
		}
	}
	return false;
}
int Maxmatch(int mid) {
	int sum = 0;
	memset(match, 0, sizeof(match));
	for (int i = K + 1; i <= K + C; i++) {
		memset(vis, 0, sizeof(vis));
		if (dfs(i, mid)) sum++;
	}
	return sum;
}
int main() {
	cin >> K >> C >> M;
	Init();
	int lef = 1, rig = mmax, mid = (lef + rig) >> 1, ans;
	while (lef <= rig) {
		Build_graph(mid);
		if (Maxmatch(mid) == C) rig = mid - 1, ans = mid;
		else lef = mid + 1;
		mid = (lef + rig) >> 1;
	}
	cout << ans << endl;
	return 0;
}

本文地址:https://blog.csdn.net/weixin_45691711/article/details/107284547