n个人,已知每个人体重。独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人。显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟?
Input
第一行包含两个正整数n (0<n<=10000)和m (0<m<=2000000000),表示人数和独木舟的承重。 接下来n行,每行一个正整数,表示每个人的体重。体重不超过1000000000,并且每个人的体重不超过m。
Output
一行一个整数表示最少需要的独木舟数。
Input示例
3 6 1 2 3
Output示例
2
题解:贪心。排序,取没用过的最后一个与没用过的最前面的一个求和,。如果<=m,ans++,否则只计算后一个,用过了就标记一下。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
#define LL long long
const LL maxm=1e5+10;
LL a[maxm];
map<LL,LL>q;
int main()
{
LL n,m;
while(scanf("%d%lld",&n,&m)!=EOF)
{
q.clear();
for(LL i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sort(a,a+n+1);
LL ans=0;
int cnt=1;
for(LL i=n;i>=1;i--)
{
if(cnt==i&&!q[a[i]])
{
ans++;
q[a[i]]=1;
}
else
{
if(!q[a[i]]&&!q[a[cnt]]&&(a[i]+a[cnt]<=m))
{
q[a[i]]=1;
q[a[cnt]]=1;
ans++;
cnt++;
}
else if(!q[a[i]])
{
q[a[i]]=1;
ans++;
}
}
}
printf("%lld\n",ans);
}
return 0;
}