# 【贪心】【P4053】[JSOI2007] 建筑抢修

## Description

$n$ 个工作，第 $i$ 个工作做完需要 $a_i$ 的时间，并且必须在 $b_i$ 时刻前完成。求最多能按时完成多少个工作

## Limitations

$1 \leq n \leq 150000$$1 \leq a_i \leq b_i \leq 2147483647$

## 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);
}

posted @ 2019-10-30 19:39  一扶苏一  阅读(198)  评论(0编辑  收藏  举报