【二分+贪心】【最小值最大化】牛牛分田地

  牛客网 https://www.nowcoder.com/questionTerminal/fe30a13b5fb84b339cb6cb3f70dca699

牛牛分田地

牛牛和 15 个朋友来玩打土豪分田地的游戏,牛牛决定让你来分田地,地主的田地可以看成是一个矩形,每个位置有一个价值。分割田地的方法是横竖各切三刀,分成 16 份,作为领导干部,牛牛总是会选择其中总价值最小的一份田地, 作为牛牛最好的朋友,你希望牛牛取得的田地的价值和尽可能大,你知道这个值最大可以是多少吗?
输入描述:
  每个输入包含 1 个测试用例。每个测试用例的第一行包含两个整数 n 和 m(1 <= n, m <= 75),表示田地的大小,接下来的 n 行,每行包含 m 个 0-9 之间的数字,表示每块位置的价值。
输出描述:
  输出一行表示牛牛所能取得的最大的价值。

示例输入
  4 4
  3332
  3233
  3332
  2323
示例输出
  2

  这道题也是典型的最大值最小化,或最小值最大化问题。这里是让16块田地中最小的值最大化。
  依然使用二分+贪心的方法,每次尝试一个 min_v,循环是 while(l <= r),最后输出 l - 1
  注意输入是连着的,所以需要用char类型读入,且为为了快速计算每一块的面积,使用一个pre_sum数组记录以每一个位置为右下角的矩形的值。
  读入的田地数据如下:

0 0 0 0 0
0 3 3 3 2
0 3 2 3 3
0 3 3 3 2
0 2 3 2 3

  计算出的 pre_sum 数组如下:

0 0 0 0 0
0 3 6 9 11
0 6 11 17 22
0 9 17 26 33
0 11 22 33 43

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>    // INT_MAX
using namespace std;

int rows, cols;				  // 行、列
vector<vector<int>> f;		  // fields 田地
vector<vector<int>> pre_sum;  // 为了快速计算每一块的值

inline int calc(int x1, int y1, int x2, int y2) {
	return pre_sum[x2][y2] - pre_sum[x2][y1] - pre_sum[x1][y2] + pre_sum[x1][y1];
}

int canDivide(int min_v) {
	for (int x1 = 1; x1 <= rows - 3; x1++)
		for (int x2 = x1 + 1; x2 <= rows - 2; x2++)
			for (int x3 = x2 + 1; x3 <= rows - 1; x3++) {
				int cnt = 0, rec = 0;
				for (int y = 1; y <= cols; y++)	{
					if (calc(0,  rec, x1,   y) >= min_v &&
						calc(x1, rec, x2,   y) >= min_v &&
						calc(x2, rec, x3,   y) >= min_v &&
						calc(x3, rec, rows, y) >= min_v) 
					{
						++cnt;
						rec = y;
					}
				}
				if (cnt >= 4)
					return true;
			}
	return false;
}

int main() {
	char ch;
	int l = INT_MAX, r = 0;
	cin >> rows >> cols;
	getchar();	// 读掉换行
	f = vector<vector<int>>(rows + 1, vector<int>(cols + 1, 0));  // fileds
	pre_sum = vector<vector<int>>(rows + 1, vector<int>(cols + 1, 0));
	for (int i = 1; i <= rows; ++i) {
		for (int j = 1; j <= cols; ++j) {
			cin >> ch;
			f[i][j] = ch - '0';
			pre_sum[i][j] = pre_sum[i][j - 1] + pre_sum[i - 1][j] - pre_sum[i - 1][j - 1] + f[i][j];
			l = min(l, f[i][j]);
			r += f[i][j];
		}
		getchar();	// 读掉换行
	}
	while (l <= r) {
		const int mid = l + (r - l) / 2;
		// 尝试16块中每一块都>=mid 可不可行
		if (canDivide(mid)) l = mid + 1;
		else                r = mid - 1;
	}
	cout << l - 1 << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值