51Nod - 1432 一支独木

n个人,已知每个人体重。独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人。显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟?

Input

第一行包含两个正整数n (0 接下来n行,每行一个正整数,表示每个人的体重。体重不超过1000000000,并且每个人的体重不超过m。

Output

一行一个整数表示最少需要的独木舟数。

Sample Input

3 6
1
2
3

Sample Output

2

解题思路:从小到大排序,每一次找一个最大的和一个最小的,如果两个数相加小于m,就让结果ans加1,否则就让最重的那个重的人单独一个船 ,一道简单的水题,在排序的时候自己写了个快排,复习了下快排

AC代码:

#include<iostream>
using namespace std;
const int maxn=1e4+10;
int a[maxn];
void quicksort(int left,int right)//快速排序 
{
	int low=left,high=right;
	if(low>=high)
		return;//递归结束条件 
	int x=a[low];//x用来保存枢轴记录 
	while(low<high)
	{
		while(low<high&&a[high]>=x)
			high--;
		a[low]=a[high];
		while(low<high&&a[low]<=x)
			low++;
		a[high]=a[low];
	}
	a[low]=x;
	quicksort(left,low-1);
	quicksort(low+1,right);
}
int main()
{
	int n,m,low,high;
	int ans=0;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	quicksort(0,n-1);//从小到大排序 
	int left=0,right=n-1;
	while(left<=right)
	{
		if(a[left]+a[right]<=m)
		{
			ans++;
			left++;
			right--;
		}
		else
		{
			ans++;
			right--;
		}		
	}
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40707370/article/details/85041709
今日推荐