LA 7587. ACM-ICPC World Finals 2016 L. Swap Space

贪心

#include <cstdio>
#include <algorithm>
using std::sort;

#define kN 1000000

struct vv {
  int a, b;
  vv(int a = 0, int b = 0): a(a), b(b) {}
}p[kN], q[kN];

bool cmp1(vv xx, vv yy) {
  if (xx.a == yy.a)
    return xx.b > yy.b;
  return xx.a < yy.a;
}
bool cmp2(vv xx, vv yy) {
  if (xx.b == yy.b)
    return xx.a < yy.a;
  return xx.b > yy.b;
}

int main() {
  int n, cnt1 = 0, cnt2 = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    int s, t;
    scanf("%d%d", &s, &t);
    if (s < t)
      p[cnt1++] = vv(s, t);
    else
      q[cnt2++] = vv(s, t);
  }
  sort(p, p + cnt1, cmp1);
  sort(q, q + cnt2, cmp2);
  long long ans = 0, space = 0;
  for (int i = 0; i < cnt1; i++) {
    space -= p[i].a;
    if (space < 0) {
      ans += -space;
      space = 0; 
    }
    space += p[i].b;
  }
  for (int i = 0; i < cnt2; i++) {
    space -= q[i].a;
    if (space < 0) {
      ans += -space;
      space = 0; 
    }
    space += q[i].b;
  }
  printf("%lld\n", ans);
  return 0;
}
posted @ 2017-12-31 22:47  Planet6174  阅读(586)  评论(0编辑  收藏  举报