题目描述
元旦快到了,校学生会让乐乐负责新年晚会的纪念品发放工作。为使得参加晚会的同学所获得 的纪念品价值相对均衡,他要把购来的纪念品根据价格进行分组,但每组最多只能包括两件纪念品, 并且每组纪念品的价格之和不能超过一个给定的整数。为了保证在尽量短的时间内发完所有纪念品,乐乐希望分组的数目最少。
你的任务是写一个程序,找出所有分组方案中分组数最少的一种,输出最少的分组数目。
输入输出格式
输入格式:
共n+2行:
第1行包括一个整数w,为每组纪念品价格之和的上上限。
第2行为一个整数n,表示购来的纪念品的总件数G。
第3至n+2行每行包含一个正整数Pi(5≤Pi≤w)表示所对应纪念品的价格。
输出格式:
一个整数,即最少的分组数目。
输入输出样例
输入样例#1: 复制
100 9 90 20 20 30 50 60 70 80 90
输出样例#1: 复制
6
说明
50%的数据满足:1≤n≤15
100%的数据满足:1≤n≤30000,80≤w≤200
题解:
先从大到小排一下序,然后一个 伪指针 i 指向最大的 伪指针j 指向最小的元素,然后看看最大的能不能和最小的放一个
小组,并且价格小于等于w ,小于等于的话,j-- ,否则 i++ ,j不变,依次进行直到 i == j ;当然可能数据有点水.
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <set>
#include <cstring>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#define Swap(a,b) a ^= b ^= a ^= b
#define cl(a,b) memset(a,b,sizeof(a))
using namespace std ;
typedef long long LL;
const int N = 1e7+10 ;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
const int MAX = 30010;
const int inf = 0xffffff;
const LL mod = 1e9+7 ;
priority_queue<int,vector<int>,greater<int> > q ;// 小跟堆
priority_queue<int> Q ; // 大堆
int p[MAX] ;
bool cmp(const int &a , const int &b){
return a>b;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
int w , n ;
cin >> w >> n ;
for(int i = 1 ; i<=n;i++){
cin >>p[i] ;
}
sort(p+1,p+1+n,cmp);
int ans = 0 ;
int j = n ;
int num = 0 ;
int sum = 0 ;
for(int i = 1 ;i <=n ;i++){
sum =p[i] ;
num = 0 ;
while(sum+p[j]<=w ){
sum+=p[j] ;
j--;
num++ ;
if(num == 2 ){
// 数据有点水,不加也能过
break;
}
}
if(i<j)
ans++;
}
cout<<ans +1;
return 0;
}