[LightOJ] [1076] Get the Containers

Problem Description

Loading...

Problem Analysis

Divide the n numbers into m groups
Find the minimum among all possible maximum sums

Binary search idea
Search for the result in the interval l~r

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdio.h>
int a[1200];
int n,m;
bool judge(int t) {
	int cnt=1;
	int sum=0;
	for(int i=0; i<n; i++) {
		if(sum+a[i]>t) {
			cnt++;
			sum=0;
		}
		sum+=a[i];
	}
	if(cnt<=m)
		return true;
	else
		return false;
}
int main() {
	int T,kase=0;
	scanf("%d",&T);
	while(T--) {
		scanf("%d %d",&n,&m);
		int max=0,sum=0;
		for(int i=0; i<n; i++) {
			scanf("%d",&a[i]);
			sum+=a[i];
			if(max<a[i])
				max=a[i];
		}
		int l=max,r=sum;
		int res=max;
		while(r>=l) {
			int mid=(l+r)/2;
			if(judge(mid)) {
				res=mid;
				r=mid-1;
			} else
				l=mid+1;
		}
		printf("Case %d: %d\n",++kase,res);
	}
	return 0;
}

Problem link:【Light】[1076 ]Get the Containers

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...