纪念品分组

题目链接

sol

尽量把大的和小的放一起,先放大的后放小的,两个指针向中间移动

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#define rep(i,l,r) for(int i=l;i<=r;++i)
#define per(i,l,r) for(int i=l;i>=r;--i)
using namespace std;
int w,n,p[30010];
int ()
{
int l,r,temp,ans=0;
scanf("%d%d",&w,&n);
l=1,r=n;
rep(i,1,n)scanf("%d",&p[i]);
sort(p+1,p+n+1);
while(l<=r)
{
++ans;
temp=0;
while(r>=l&&temp+p[r]<=w)
temp+=p[r--];
while(l<=r&&temp+p[l]<=w)
temp+=p[l++];
}
cout<<ans;
}