题目:[NOIP2007]纪念品分组 (nowcoder.com)

#include<bits/stdc++.h>
#define int long long
#define PII pair<int,int>
#define LL__int 128
 using namespace std;
 
 const int N=2e5+10,M=998344353;
 int a[N];
 

 signed main()
 {
 	std::ios::sync_with_stdio(false);
 	std::cin.tie(NULL);
 	
	 int w,n;
	 cin>>w>>n;
	 for(int i=1;i<=n;i++)
	 {
	 	cin>>a[i];
	 }
	 sort(a+1,a+n+1); //价格从低到高 
	 int cnt=0;
	 int l=1,r=n;
	 while(l<=r) 
	 {
	 	if(a[l]+a[r]<=w) 
	 	{
	 		l++;
	 		r--;
	 		cnt++;
		 }else
		 {
		 	r--; 
		 	cnt++; //计数器加1,a[r]自己为一组 
		 }
	 }
	 cout<<cnt<<endl;
 }

从这道题学到的:

  • 双指针在数组中的应用
  • while的灵活循环

更多推荐