NYOJ 71 乘船问题【贪心】
时间复杂度O(n)
有n个人,第i个人的重量为w[i],每艘船的最大载重量均为c,且最多只能乘两个人。用最少的船装载所有人。
思路:从最轻的开始考虑,让最轻的和最重的一条船,若超出重量则可判定最重的只能一人一条船
#include<cstdio> #include<string> #include<cstdlib> #include<cmath> #include<iostream> #include<cstring> #include<set> #include<queue> #include<algorithm> #include<vector> #include<map> #include<cctype> #include<stack> #include<sstream> #include<list> #include<assert.h> #include<bitset> #include<numeric> #define debug() puts("++++") #define gcd(a,b) __gcd(a,b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define fi first #define se second #define pb push_back #define sqr(x) ((x)*(x)) #define ms(a,b) memset(a,b,sizeof(a)) #define sz size() #define be begin() #define pu push_up #define pd push_down #define cl clear() #define lowbit(x) -x&x #define all 1,n,1 #define rep(i,n,x) for(int i=(x); i<(n); i++) #define in freopen("in.in","r",stdin) #define out freopen("out.out","w",stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e18; const int maxn = 1e3 + 20; const int maxm = 1e6 + 10; const double PI = acos(-1.0); const double eps = 1e-8; const int dx[] = {-1,1,0,0,1,1,-1,-1}; const int dy[] = {0,0,1,-1,1,-1,1,-1}; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int n,m; int a[maxn]; int main() { int t; cin>>t; while(t--){ memset(a,0,sizeof(a)); int w,cnt=0; cin >> w >> n; //人数、载重量 for(int i=0; i<n; i++) cin>>a[i]; sort(a,a+n); int i=0,j=n-1; while(i<=j) { if(a[i]+a[j]>w){ cnt++; j--; } else{ cnt++; i++; j--; } } cout << cnt << endl; } }