二分——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;
}