Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.
Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively.
The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.
Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.
2 1 2 5
7
4 3 2 3 5 9
9
3 2 3 5 7
8
In the first sample, Kevin must pack his two cowbells into the same box.
In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.
In the third sample, the optimal solution is {3, 5} and {7}.
题目大意: 就是给你n个物品,每个物品大小为si ,s(i) <= s(i+1),然后k个箱子,然后每个箱子中最多只能放两件物品,问箱子在可以将物体全部放入的时候的最小大小是多少。
这个题目是一个简单的贪心题目,我刚开始没看到一个箱子最多只能放两个,所以纠结了挺久的,不过后来看到了 那就可以写了
首先,最大的物品如果能单独放就单独放 不能单独放的 就和最小的放在一起,比如 n = 4 , k = 2 那么肯定是 s1 与s4,s2 与s3这样放会是最优的
所以照着这个思路,就可以写了
上代码
#include <stdio.h>
#include <string.h>
int num[100010];
int main()
{
int n,k;
while (~scanf("%d%d",&n,&k ) )
{
for (int i = 1 ; i <= n ; i++ )
{
scanf("%d",&num[i] );
}
int temp = num[n]; //这个先初始化为最大物品的大小,因为箱子肯定大于等于这个值
int count = k * 2 - n ; //可以单独放的物品有几个
int temp1 = 0;
if ( count < n) //如果有发生一个箱子放两件物品的情况
{
int a;
int l = 1; //最小能放物品的下标
for (int i = n - count ; i >= 1 ; i-- ) //这些都是和另一个物品同放在一个箱子中的物品
{
if ( l == i ) break; //如果相同话 就说明 放完了
a = num[i] + num[l]; //头与尾放在一起
if (temp1 < a )
{
temp1 = a; //记录需要的最大尺寸
}
l++;
}
}
printf("%d\n",temp <= temp1 ? temp1 : temp); //输出最大的
}
return 0;
}