Codeforces Round #178 (Div. 2) B .Shaass and Bookshelf

Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights.

Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.

Help Shaass to find the minimum total thickness of the vertical books that we can achieve.

Input

The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers ti and wi denoting the thickness and width of the i-th book correspondingly, (1 ≤ ti ≤ 2, 1 ≤ wi ≤ 100).

Output

On the only line of the output print the minimum total thickness of the vertical books that we can achieve.

Sample Input

Input

51 121 32 152 52 1

Output

5

Input

31 102 12 4

Output

3

题意:

给你N本书,每本书由一个厚度t[i](1或者2),宽度w[i],高度都是一样,把一些书竖着放,然后一些书横着放在同一层。问你把全部的书放好之后竖着的书的总厚度是多少?

思路:

每本书的厚度要么为1要么为2。因此我们能够依据书的厚度分为两类,然后每类按书的宽度从大到小排序,然后用二重循环进行枚举,把厚度为1的前i个和厚度为2的前j个竖着放,其它的横着放,在横着放的总宽度不超过竖着放的总厚度的前提下,求出一个竖着放总厚度最小的值来。这就是终于答案.

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define INF 0x1f1f1f1f
int a[1001];
int b[1001];
int f[1001];
int main()
{
    int n,V,i,j;
    while(scanf("%d",&n)!=EOF)
    {
        V=0;
        for(i=0;i<n;i++)
        {
            scanf("%d%d",&b[i],&a[i]);
            V=V+b[i];
        }
        for(i=0;i<=V;i++)
        f[i]=INF;
        f[0]=0;     
        for(i=0;i<n;i++)
        for(j=V;j>=b[i];j--)
        f[j]=min(f[j],f[j-b[i]]+a[i]);
        for(i=V;i>=0;i--)
        {
            if(V-i>=f[i])break;
        }
        printf("%d
",V-i);
    }
    return 0;
}




原文地址:https://www.cnblogs.com/mfmdaoyou/p/7211682.html