Uva1149

每个bin最多只能放两个,所以最佳的贪心策略是从大的开始放,如果有空间放第二个,尽量放最大的。

 1 #include <bits/stdc++.h>
 2
 3 using namespace std;
 4
 5 const int maxn = 100000 + 10;
 6
 7 int t;
 8
 9 int n,l;
10
11 int a[maxn];
12
13 int b[maxn];
14
15 int flag[maxn];
16
17 void solve(){
18     int cnt = 0;
19     memset(flag, 0, sizeof(flag));
20     for(int i = 1; i <= n; ++i){
21             if(flag[i]){
22                 continue;
23             } else {
24                 ++cnt;
25                 flag[i] = 1;
26                 int temp = l - a[i];
27                 int loc = upper_bound(b+1, b+1+n, temp) - b;
28                 if(loc == 1+n) loc = n;
29                 for(int j = loc; j >= 1; --j){
30                     if(!flag[n-j+1] && b[j] <= temp){
31                         flag[n-j+1] = 1;
32                         break;
33                     }
34                 }
35             }
36     }
37     printf("%d\n",cnt);
38     if(t) printf("\n");
39 }
40
41 bool cmp(int a, int b){
42     return a > b;
43 }
44
45 int main(){
46         scanf("%d",&t);
47         while(t--){
48             scanf("%d%d",&n,&l);
49             for(int i = 1; i <= n; ++i){
50                 scanf("%d",&a[i]);
51                 b[i] = a[i];
52             }
53             if(l == 0){
54                 printf("0\n");
55                 continue;
56             }
57             sort(a+1, a+1+n, cmp);
58             sort(b+1, b+1+n);
59             solve();
60         }
61 }
时间: 2024-10-12 16:52:26

Uva1149的相关文章

UVa1149 Bin Packing (贪心)

链接:http://vjudge.net/problem/UVA-1149 分析:贪心的放,先放重的,剩下的容量看能不能放进一个轻的. 1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 const int maxn = 100000 + 5; 6 7 int a[maxn]; 8 9 int main() { 10 int T; 11 scanf("%d", &T)

UVA-1149 Bin Packing (贪心)

题目大意:给定n个物品的重量,无限个容量为m的箱子,每个箱子最多装两个物品,要把所有的物品都装下,最少需要多少个箱子. 题目分析:贪心策略:每次将最重和最轻的两个物品放到一个箱子里,如果装不下,则将最重的单独装到一个箱子里. 代码如下: # include<iostream> # include<cstdio> # include<cstring> # include<algorithm> using namespace std; int a[100005]

[UVA1149]Dominating Patterns

Description The archaeologists are going to decipher a very mysterious ``language". Now, they know many language patterns; each pattern can be treated as a string on English letters (only lower case). As a sub string, these patterns may appear more t

UVa 1149 装箱

https://vjudge.net/problem/UVA-1149 题意:给定N个物品的重量和背包的容量,同时要求每个背包最多装两个物品.求至少需要的背包数. 思路:很简单的贪心.每次将最轻的和最重的放一个背包里,如果放不下,则只放一个最重的. 1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 5 const int maxn = 100000 + 5; 6 7 int n, m; 8 int

算法竞赛入门经典(第八章)

习题8-1 Uva1149 11.8 #include <iostream> #include <algorithm> using namespace std; int main() { int n, m, mi; int w[100005]; int num; int l, r; cin>>n>>m; for(int i = 1; i <= n; i++) { cin>>w[i]; } sort(w+1, w+n+1); l = 1 ,