C - Chocolate Bar
Time limit : 2sec / Memory limit : 256MB
Score : 400 points
Problem Statement
There is a bar of chocolate with a height of H blocks and a width of W blocks. Snuke is dividing this bar into exactly three pieces. He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.
Snuke is trying to divide the bar as evenly as possible. More specifically, he is trying to minimize Smax - Smin, where Smax is the area (the number of blocks contained) of the largest piece, and Smin is the area of the smallest piece. Find the minimum possible value of Smax−Smin.
Constraints
- 2≤H,W≤105
Input
Input is given from Standard Input in the following format:
H W
Output
Print the minimum possible value of Smax−Smin.
Sample Input 1
3 5
Sample Output 1
0
In the division below, Smax−Smin=5−5=0.
![2a9b2ef47b750c0b7ba3e865d4fb4203.png](https://i-blog.csdnimg.cn/blog_migrate/f628ee11cf88bce20cf3835357963135.png)
Sample Input 2
4 5
Sample Output 2
2
In the division below, Smax−Smin=8−6=2.
![a42aae7aaaadc4640ac5cdf88684d913.png](https://i-blog.csdnimg.cn/blog_migrate/dd6ef1cce932e7cd53d957828f35f1b5.png)
Sample Input 3
5 5
Sample Output 3
4
In the division below, Smax−Smin=10−6=4.
![eb0ad0cb3185b7ae418e21c472ff7f26.png](https://i-blog.csdnimg.cn/blog_migrate/c97546f411dae1047c6e1076aac69d9c.png)
Sample Input 4
100000 2
Sample Output 4
1
Sample Input 5
100000 100000
Sample Output 5
50000
思路:割法无非就两种,平行割三刀,或者先割一刀分成两半1和2,再在其中一半横着割一刀分成1,3,4,那么比较这俩情况就行了,对于第二种情况,最小的矩形要么是1要么是3或4,再分这两种情况计算就行了。
# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int cal(int a, int b)
{
int c = a/2;
if((LL)a+c > (LL)b*c)
return (int)((LL)a+c-(LL)b*c);
int x = (int)ceil(b*c*1.0/(a+c));
return max((a+c)*x-b*c, (b-x)*(a-2*c));
}
int cal2(int a, int b)
{
int c = (int)ceil(a/2.0);
if(a+c > (LL)b*c) return 1e9;
int x = (LL)b*c/(c+a);
return max((int)((LL)b*c-(LL)x*(a+c)), (int)((LL)(b-x)*(2*c-a)));
}
int cal3(int a, int b)
{
double x = floor(b/3.0);
double y = ceil(b/3.0);
return (int)(y*a-x*a);
}
int main()
{
int a, b;
scanf("%d%d",&a,&b);
int ans = min(cal(a, b), min(cal(b, a), min(cal2(a, b), min(cal2(b, a), min(cal3(a, b), cal3(b, a))))));
printf("%d\n",ans);
return 0;
}