洛谷 P1094 纪念品分组



水题 结合题意双指针夹逼


#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

const int MAXN = 3e4 + 10;

int arr[MAXN];

void ksort(int *arr, int fst, int lst)
{
	int i = fst, j = lst, mid = arr[(i + j) / 2];
	
	while(i <= j)
	{
		while(arr[i] < mid)
			i++;
			
		while(arr[j] > mid)
			j--;
			
		if(i <= j)
		{
			swap(arr[i], arr[j]);
			i++;
			j--;
		}
	}
	
	if(i < lst)
		ksort(arr, i, lst);
		
	if(j > fst )
		ksort(arr, fst, j);
}


int main()
{
	int mc;
	cin>>mc;
	
	int n;
	cin>>n;
	
	for(int i = 0; i < n; i++)
		 cin>>arr[i];
	
	ksort(arr, 0, n - 1);
		 
	int fst = 0, lst = n - 1, ans = 0;
	
	while(fst <= lst)
	{
		if(arr[fst] + arr[lst] <= mc)
		{
			ans++;
			fst++;
			lst--;
		}
		
		else
		{
			ans++;
			lst--;
		}
	}
	
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zeolim/article/details/81015953
今日推荐