AcWing430 纪念品分组 -- 双指针

#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define SZ(x) (int) (x).size()
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> VI;
typedef double db;

const int N = 30010;
int n, w, a[N];
void solve() {
  cin >> w >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  sort(a+1, a+1+n);
  int res = 0;
  int i = 1, j = n;
  while (i < j) {
    if (a[i]+a[j] <= w) i++;
    res++;
    j--;
  }
  if (i == j) res++; // 最后的i和j相等的一组
  cout << res << '\n';
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  solve();
  return 0;
}

posted on 2022-10-17 15:56  chelly酱  阅读(13)  评论(0)    收藏  举报

导航