二分——Brownie Slicing

题目链接

二分——Brownie Slicing

题目描述

Bessie has baked a rectangular brownie that can be thought of as an RxC grid (1 <= R <= 500; 1 <= C <= 500) of little brownie squares. The square at row i, column j contains Nij(0 <= Nij <= 4,000) chocolate chips.
Bessie wants to partition the brownie up into AB chunks (1 <= A <= R; 1 <= B <= C): one for each of the AB cows. The brownie is cut by first making A-1 horizontal cuts (always along integer coordinates) to divide the brownie into A strips. Then cut each strip independently with B-1 vertical cuts, also on integer boundaries. The other A*B-1 cows then each choose a brownie piece, leaving the last chunk for Bessie. Being greedy, they leave Bessie the brownie that has the least number of chocolate chips on it.
Determine the maximum number of chocolate chips Bessie can receive, assuming she cuts the brownies optimally.
As an example, consider a 5 row x 4 column brownie with chips
distributed like this:
在这里插入图片描述
Bessie must partition the brownie into 4 horizontal strips, each with two pieces. Bessie can cut the brownie like this:

在这里插入图片描述
Thus, when the other greedy cows take their brownie piece, Bessie still gets 3 chocolate chips.

输入描述

Line 1: Four space-separated integers: R, C, A, and B
Lines 2…R+1: Line i+1 contains C space-separated integers: Ni1,…,NiC

输出描述

Line 1: A single integer: the maximum number of chocolate chips that Bessie guarantee on her brownie

示例

输入

5 4 4 2
1 2 2 1
3 1 1 1
2 0 1 3
1 1 1 1
1 1 1 1

输出

3

题目大意

给定一个 R 行 C 列的矩形,将其分成 A * B 块,我们需要找到最小块的最大值。

分析

二分答案,然后用贪心判断是否能切成 A * B 块。

#include<bits/stdc++.h>
using namespace std;
int r,c,a,b,f[505][505],s[505][505];

int check(int mid)
{
	int cnta=0,cntb=0,flaga=1,flagb=1,sum=0;
	for(int i=1;i<=r;i++){
		flagb=1;
		cntb=0;
		for(int j=1;j<=c;j++){
			sum=s[i][j]-s[flaga-1][j]-s[i][flagb-1]+s[flaga-1][flagb-1];
			if(sum>=mid){	// 当和大于或等于 mid 时,就可以切开 
				flagb=j+1;	// 更新 flagb 
				cntb++;
			}
		}
		if(cntb>=b){	// 如果可以切 b 块,则将 cnta 加一,并更新 flaga 
			cnta++;
			flaga=i+1;
		}
	}
	if(cnta>=a){	// 判断是否满足需要切的行数,若满足则返回 1 
		return 1;
	}
	return 0;
}

int main()
{
	cin>>r>>c>>a>>b;
	for(int i=1;i<=r;i++){
		int m=0;
		for(int j=1;j<=c;j++){
			cin>>f[i][j];
			m+=f[i][j];
			s[i][j]=s[i-1][j]+m;	// 前缀和 
		}
	}
	int left=0,right=s[r][c],ans;
	while(left<=right){		// 二分 
		int mid=(left+right)/2;
		if(check(mid)){
			left=mid+1;
			ans=mid;
		}
		else{
			right=mid-1;
		}
	}
	cout<<ans<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值