【貪心】【P4053】[JSOI2007] 建築搶修

【貪心】【P4053】[JSOI2007] 建築搶修

Description

\(n\) 個工作,第 \(i\) 個工作做完需要 \(a_i\) 的時間,並且必須在 \(b_i\) 時刻前完成。求最多能按時完成多少個工作

Limitations

\(1 \leq n \leq 150000\)\(1 \leq a_i \leq b_i \leq 2147483647\)

Solution

隨機跳題跳到一個看上去很經典的貪心,以前只聽說過從來沒做到過題。

首先一個顯然的結論是,對於完成工作的順序序列 \(p\),如果我將 \(p\) 裏面的元素按照 \(b_i\) 單調不降的順序排序,得到的序列一定也是一個合法的能夠完成序列內所有工作的序列。證明上可以考慮相鄰兩項,如果前面一項比後面一項的 \(b\) 大,那麼交換相鄰兩項一定也可以完成任務。數學歸納得到按照 \(b\) 的不降序排序是合法的。例如,如果 \(\{1,~5,~3\}\) 的順序可以完成 \(3\) 項任務,並且 \(b_1 \leq b_3 \leq b_5\),那麼 \(\{1,~3,~5\}\) 一定也可以完成三項任務。

因此我們直接對任務序列按照 \(b\) 不降序排序,依次考慮是否選擇每個任務。

考慮枚舉到一個任務時,如果我們已經選擇的任務用時加上該任務的用時不會超出該任務的時限,那麼我們先貪心的將它選入任務序列。

考慮如果選入這個任務超時了,那麼我們考慮將前面一個任務去掉,從而讓這個任務被選入。顯然所有任務的總用時越低越好,因從我們考慮去掉前面用時最長的任務,如果前面用時最長的任務比當前任務用時長,那麼去掉前面的任務後當前任務一定能被選入,因爲總用時減少但是時限增加了。並且我們在保證任務總數不變的情況下儘可能減少了總用時。因此這個貪心是正確的。當然如果前面最長的不如當前用時長,那就不再選入當前任務。

用堆去維護所有被選入的任務的時常即可。時間複雜度 \(O(n \log n)\)

Code

#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#ifdef ONLINE_JUDGE
#define freopen(a, b, c)
#define int ll
#endif

typedef long long ll;

namespace IPT {
  const int L = 1000000;
  char buf[L], *front=buf, *end=buf;
  char GetChar() {
    if (front == end) {
      end = buf + fread(front = buf, 1, L, stdin);
      if (front == end) return -1;
    }
    return *(front++);
  }
}

template <typename T>
inline void qr(T &x) {
  char ch = IPT::GetChar(), lst = ' ';
  while ((ch > '9') || (ch < '0')) lst = ch, ch=IPT::GetChar();
  while ((ch >= '0') && (ch <= '9')) x = (x << 1) + (x << 3) + (ch ^ 48), ch = IPT::GetChar();
  if (lst == '-') x = -x;
}

namespace OPT {
  char buf[120];
}

template <typename T>
inline void qw(T x, const char aft, const bool pt) {
  if (x < 0) {x = -x, putchar('-');}
  int top=0;
  do {OPT::buf[++top] = static_cast<char>(x % 10 + '0');} while (x /= 10);
  while (top) putchar(OPT::buf[top--]);
  if (pt) putchar(aft);
}

const int maxn = 150005;

int n, timeused, ans;
int A[maxn], B[maxn], MU[maxn];

struct Cmp {
  inline bool operator()(const int a, const int b) {
    return (A[a] == A[b]) ? (a < b) : (A[a] < A[b]);
  }
};

bool cmp(const int x, const int y);
std::priority_queue<int, std::vector<int>, Cmp> Q;

signed main() {
  freopen("1.in", "r", stdin);
  qr(n);
  for (int i = 1; i <= n; ++i) {
    qr(A[i]); qr(B[i]); MU[i] = i;
  }
  std::sort(MU + 1, MU + 1 + n, cmp);
  for (int p = 1, i = MU[p]; p <= n; i = MU[++p]) {
    if ((timeused + A[i]) > B[i]) {
      if (A[Q.top()] > A[i]) {
        timeused -= A[Q.top()];
        Q.pop();
        --ans;
      }
    }
    if ((timeused + A[i]) <= B[i]) {
      Q.push(i);
      timeused += A[i];
      ++ans;
    }
  }
  qw(ans, '\n', true);
  return 0;
}

inline bool cmp(const int x, const int y) {
  return (B[x] != B[y]) ? (B[x] < B[y]) : (x < y);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章