codeforces 294B Shaass and Bookshelf

B. Shaass and Bookshe
time limit per test    2 seconds
memory limit per test 256 megabytes
input   standard input
output  standard output

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 thei-th book isti and its pages' width is equal towi. The thickness of each book is either1 or2. 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.

codeforces 294B Shaass and Bookshelf_第1张图片

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 nextn lines contains two integersti andwi denoting the thickness and width of thei-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 test(s)
Input
5
1 12
1 3
2 15
2 5
2 1
Output
5
Input
3
1 10
2 1
2 4
Output
3
  昨天晚上处理好软件工程的作业后,都很晚了 ,就开始做这题,做到这题的时候,实在是太困了,本想着用贪心,可是一时想不出策略,就睡了。 今天早上起来想了想,这题好像是用背包能搞,n=100, 并且t都是2 的时候,最大值也就是200, 完全可以看成是一个容量为v=200的背包,然后从1开始枚举,背包的容量是1-200,背包的大小就是所求t和,只要找到结果肯定是最小的。 背包里面: 正好能将其装满,将w看成价值,此价值最大, 只要剩下的w和<=枚举的背包大小就可以了
#include 
#include 
#include 
struct num
{
    int v,w;
}a[1000];
int V[1000],s,n,sum_val;
int INF=0x7ffffff;
int main()
{
    int ZeroOnePack(int v);
    int i,j,m,t,k;
    while(scanf("%d",&n)!=EOF)
    {
        s=0;
        sum_val=0;
        for(i=1;i<=n;i++)
        {
            scanf("%d %d",&a[i].v,&a[i].w);
            s+=a[i].v;
            sum_val+=a[i].w;
        }
        for(i=1;i<=s;i++)
        {
            k=ZeroOnePack(i);
            if(k==1)
            {
                break;
            }
        }
        printf("%d\n",i);
    }
    return 0;
}
int ZeroOnePack(int v)
{
    int i,j;
    V[0]=0;
    for(i=1;i<=v;i++)
    {
        V[i]=-INF;
    }
    for(i=1;i<=n;i++)
    {
        for(j=v; j>=a[i].v; j--)
        {
            if(V[j]<(V[j-a[i].v]+a[i].w))
            {
                V[j]=V[j-a[i].v]+a[i].w;
            }
        }
    }
    if(v>=(sum_val-V[v]))
    {
        return 1;
    }
    return 0;
}

你可能感兴趣的:(Codeforces)