ZOJ-3410Layton's Escape(优先队列+贪心)
Professor Layton is a renowned archaeologist from London's Gressenheller University. He and his apprentice Luke has solved various mysteries in different places.
Unfortunately, Layton and Luke are trapped in a pyramid now. To escape from this dangerous place, they need to pass N traps. For each trap, they can use Ti minutes to remove it. If they pass an unremoved trap, they will lose 1 HP. They have K HP at the beginning of the escape and they will die at 0 HP.
Of course, they don't want trigger any traps, but there is a monster chasing them. If they haven't pass the ith trap in Di minutes, the monster will catch and eat them. The time they start to escape is 0, and the time cost on running will be ignored. Please help Layton to escape from the pyramid with the minimal HP cost.
Input
There are multiple test cases (no more than 20).
For each test case, the first line contains two integers N and K (1 <= N <= 25000, 1 <= K <= 5000), then followed by N lines, the ith line contains two integers Ti and Di (0 <= Ti <= 10^9, 0 <= Di <= 10^9).
Output
For each test case, if they can escape from the pyramid, output the minimal HP cost, otherwise output -1.
Sample Input
3 2
40 60
60 90
80 120
2 1
30 120
60 40
Sample Output
1
-1
题意:Layton逃脱需要通过N个陷阱,对于i号陷阱, 可以选择花Ti时间移除,或者不移除而损失1点血,并且必须在时间Di内通过。 题目要求通过所有陷阱最少要损失多少血,如果血量小于0,输出-1。
思路:贪心:按照Di从小到大对所有陷阱排序(迫在眉睫的先搞)。并且用费一滴血的情况来替代最大移除陷阱的时间。
优先队列:保存最大移除陷阱的时间。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstdlib> 4 #include <algorithm> 5 #include <ctime> 6 #include <cmath> 7 #include <string> 8 #include <cstring> 9 #include <stack> 10 #include <queue> 11 #include <list> 12 #include <vector> 13 #include <map> 14 #include <set> 15 #define LL long long 16 #define INF 0x3f3f3f3f 17 #define PI 3.1415926535897932384626 18 #define eps 1e-10 19 #define maxm 400007 20 #define maxn 100007 21 22 using namespace std; 23 int n,k; 24 struct Trap 25 { 26 int t; 27 int d; 28 }; 29 int cmp(Trap a,Trap b) 30 { 31 return a.d<b.d; 32 } 33 struct Temp 34 { 35 int value; 36 int pos; 37 }; 38 Temp temp[maxm]; 39 Trap trap[maxm]; 40 int main() 41 { 42 while(~scanf("%d%d",&n,&k)) 43 { 44 int num=0; 45 for(int i=0;i<n;i++) 46 { 47 scanf("%d%d",&trap[i].t,&trap[i].d); 48 } 49 sort(trap,trap+n,cmp); 50 int time=0; 51 int cnt=0; 52 priority_queue<int>q; 53 for(int i=0;i<n;i++) 54 { 55 time+=trap[i].t; 56 q.push(trap[i].t); 57 if(time>trap[i].d)//当遇到要费一滴血的情况时,我们肯定要用这一滴血换取最大效益(即减去前面的最大时间)。 58 { 59 int p=q.top(); 60 q.pop(); 61 time-=p; 62 k--; 63 cnt++; 64 } 65 //q.push(trap[i].t); 66 67 } 68 if(k>0) 69 printf("%d\n",cnt); 70 else 71 printf("-1\n"); 72 73 } 74 }