[Problem Description]
小刚在玩JSOI提供的一个称之为“建筑抢修”的电脑游戏:经过了一场激烈的战斗,T部落消灭了所有z部落的入侵者。但是T部落的基地里已经有N个建筑设施受到了严重的损伤,如果不尽快修复的话,这些建筑设施将会完全毁坏。现在的情况是:T部落基地里只有一个修理工人,虽然他能瞬间到达任何一个建筑,但是修复每个建筑都需要一定的时间。同时,修理工人修理完一个建筑才能修理下一个建筑,不能同时修理多个建筑。如果某个建筑在一段时间之内没有完全修理完毕,这个建筑就报废了。你的任务是帮小刚合理的制订一个修理顺序,以抢修尽可能多的建筑。
[Algorithm & Data Structure]
贪心 堆
[Analysis]
贪心策略:
先按照T2(建筑最晚什么时候修复)进行排序,然后从头到尾扫一遍,每一次都这样处理:
1.如果现在修复这栋房子能修复完,则修复
2.如果现在修复这栋房子修复不玩,则
(1)如果将已修复的房子中最大的那一个替换成现在这栋房子耗时会增多(这时候最大的修复个数却没有增多,得不偿失),则跳过
(2)如果将已修复的房子中最大的那一个替换成现在这栋房子耗时会减少(这时候最大的修复个数没有变但是耗时减少了,为后面的修复提供更多时间),则修复
用堆来维护已经修复的房子的耗时
[Code]
/**************************************************************
Problem: 1029
User: gaotianyu1350
Language: C++
Result: Accepted
Time:372 ms
Memory:3040 kb
****************************************************************/
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 151000;
struct node
{
int endTime, fixTime;
}a[MAXN];
int h[MAXN] = {0}, tot = 0, n;
int usetime = 0;
inline void swap(int &a, int &b)
{
int temp = a; a = b; b = temp;
}
inline void pushdown(int now)
{
while (now * 2 <= tot)
{
int child = now * 2;
if (child < tot && h[child] < h[child + 1])
child++;
if (h[now] < h[child])
{
swap(h[now], h[child]);
now = child;
}
else
break;
}
}
inline void pushup(int now)
{
while (now / 2 >= 1)
{
int father = now / 2;
if (h[father] < h[now])
{
swap(h[father], h[now]);
now = father;
}
else
break;
}
}
inline int del()
{
int ans = h[1];
h[1] = h[tot--];
pushdown(1);
return ans;
}
bool cmp(const node a, const node b)
{
return a.endTime < b.endTime;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d%d", &a[i].fixTime, &a[i].endTime);
sort(a + 1, a + 1 + n, cmp);
for (int i = 1; i <= n; i++)
{
if (usetime + a[i].fixTime <= a[i].endTime)
{
h[++tot] = a[i].fixTime;
pushup(tot);
usetime += a[i].fixTime;
}
else
{
if (a[i].fixTime < h[1] && usetime - h[1] + a[i].fixTime <= a[i].endTime)
{
usetime = usetime - h[1] + a[i].fixTime;
del();
h[++tot] = a[i].fixTime;
pushup(tot);
}
}
}
printf("%d\n", tot);
}