Daily brushing title (26)
Blue Bridge Cup 8th C language group B match exercises Province
Problem I: points chocolate
First a look at this problem, the data quite big ah, 100000, and there are limited resources, a look likely to be a problem until the dynamic programming.
Title somewhat similar to the format of a question and input to the first input line and respectively the number of points to the number of children of the chocolate, the next few lines of each piece of chocolate are corresponding length and width. Here I would like to write a C code easy to understand
#include<stdio.h>
int main()
{
int h[100000];
int w[100000];
int n, k;
scanf("%d%d",&n, &k);
int i;
for(i = 0; i < n; i++)
{
scanf("%d%d",&h[i],&w[i]);
}
int cnt = 0, j;
for(i = 100000; i >= 1; i--)
{
cnt = 0;
for(j = 0; j < n; j++)
{
cnt += (h[j] / i) * (w[j] / i);
}
if(cnt >= k)
{
printf("%d\n",i);
return 0;
}
}
return 0;
}
As the title limits the size of the resource, so we need to optimize the code, using binary search method, as follows
#include<stdio.h>
int main()
{
int h[100000], w[100000];
int mid, l, r;
l = 1;
r = 100001;
int cnt = 0, len = 0, i;
int n, k;
scanf("%d %d",&n, &k);
for(i = 0; i < n; i++)
scanf("%d %d",&h[i], &w[i]);
while(l <= r)
{
cnt = 0;
mid = (l + r) / 2;
for(i = 0; i < n; i++)
{
cnt += (h[i] / mid) * (w[i] / mid);
}
if(cnt >= k)
{
l = mid + 1;
len = mid;
}
else
{
r = mid - 1;
}
}
printf("%d\n", len);
return 0;
}
Results are as follows