http://codeforces.com/contest/1119/problem/B
Alyona has recently bought a miniature fridge that can be represented as a matrix with hh rows and 22 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.
An example of a fridge with h=7h=7 and two shelves. The shelves are shown in black. The picture corresponds to the first example.
Alyona has nn bottles of milk that she wants to put in the fridge. The ii -th bottle is aiai cells tall and 11 cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.
Alyona is interested in the largest integer kk such that she can put bottles 11 , 22 , ..., kk in the fridge at the same time. Find this largest kk .
Input
The first line contains two integers nn and hh (1≤n≤1031≤n≤103 , 1≤h≤1091≤h≤109 ) — the number of bottles and the height of the fridge.
The second line contains nn integers a1a1 , a2a2 , ..., anan (1≤ai≤h1≤ai≤h ) — the heights of the bottles.
Output
Print the single integer kk — the maximum integer such that Alyona can put the bottles 11 , 22 , ..., kk in the fridge at the same time. If Alyona can put all bottles in the fridge, print nn . It is easy to see that Alyona can always put at least one bottle in the fridge.
Examples
Input
5 7 2 3 5 4 1
Output
3
Input
10 10 9 1 1 1 1 1 1 1 1 1
Output
4
Input
5 10 3 1 4 2 4
Output
5
题目大意:给出冰箱的高度h,以及n个瓶子的高度,每个瓶子的宽度是1,冰箱的宽度是2,你可以在冰箱的任意位置加隔板,瓶子只能放在隔板上,(初始认为冰箱只有最底部有隔板)让你求出最大的k,满足前k个瓶子都能放到冰箱里面。
思路:二分+贪心。二分求满足题意的最大值问题,二分一个mid,表示把前mid个瓶子放到冰箱里面,瓶子的方法也很简单,对这mid个瓶子排序,从大到小(或从小到大)相邻的两个放在同一层上即可。好像这道题数据范围很小,暴力枚举mid也可以。
#include<iostream>
#include<cstdio>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int a[1005];
int b[1005];
int n,h;
//二分求 最大值
int main()
{
scanf("%d %d",&n,&h);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int l=1,r=n;
int mid;
int cnt=0;
b[0]=0;
while(l<=r)
{
mid=(l+r)>>1;
for(int i=1;i<=mid;i++)
b[i]=a[i];
sort(b+1,b+1+mid);
cnt=0;
for(int i=mid;i>=1;i-=2)
{
cnt+=b[i];
if(cnt>h)
break;
}
if(cnt>h)//不满足题意
r=mid-1;
else
l=mid+1;
}
printf("%d\n",r);
return 0;
}