CF 178(div 2)B(greedy + 枚举)

B. Shaass and Bookshelf
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 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.

CF 178(div 2)B(greedy + 枚举)_第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 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 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
 
开始想直接贪心,找到一个最优策略,后来发现是不行的。后来看了题解,把所有厚度为1,2的分别保存下来,然后对厚度相同的,肯定优先选宽度小的放在上面,所以排序后,对放在下面的厚度为1,2的个数枚举即可。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#define LL long long
using namespace std;
const int maxn = 100 + 5;
const int INF = 100000;
vector<int> w[3];

int main(){
    int n,ww,tt,total;
    while(scanf("%d",&n) != EOF){
        total = 0;
        w[1].clear();w[2].clear();
        for(int i = 0;i < n;i++){
            scanf("%d%d",&tt,&ww);
            w[tt].push_back(ww);
            total += tt;
        }
        sort(w[1].begin(),w[1].end());
        sort(w[2].begin(),w[2].end());
        int size1 = w[1].size();
        int size2 = w[2].size();
        int sum,ans = INF;
        for(int i = 0;i <= size1;i++){
            sum = 0;
            for(int k = 0;k < i;k++) sum += w[1][k];
            for(int j = 0;j <= size2;j++){
                if(j) sum += w[2][j-1];
                int len = total-i-2*j;
                if(sum <= len) ans = min(ans,len);
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(CF 178(div 2)B(greedy + 枚举))