思想
总结:
其实这道题就按正常思路想我们也是拿 最大的和最小的配对,次大的和次小的配对。
code
#include <iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
int w,n;cin>>w>>n;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+n+1); //排个序这样最小的就在前面,最大的在后面,从最前面找小的去和后面大的配对
int l=0,r=n;
int ans=0;
while(l<=r)
{
if(l==r) //两个指针相遇说明找完了都找不到配对的,退出
{
ans++; //即剩下的最后一个元素。这个元素无论如何都要被配对,所以需要将ans++。
break;
}
if(a[l]+a[r]<=w) //满足条件
{
l++,r--; //继续找下个配对的组合
ans++; //组数++
}
else
{
r--; //否则就是次小的配不了次大的,就找次次大的来配对
ans++; //组数++
}
}
cout<<ans<<endl;
return 0;
}