UVA1153-Keep the Customer Satisfied(贪心)
Posted npugen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA1153-Keep the Customer Satisfied(贪心)相关的知识,希望对你有一定的参考价值。
Accept: 222 Submit: 1706
Time Limit: 3000 mSec
Problem Description
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
Data Each test case is described by one input ?le that contains all the relevant data: The ?rst line contains the number n of orders (n can be as large as 800000 for some test cases). It is followed by n lines. Each of which describes an order made of two integer values: the amount of steel (in tons) required for the order (lower than 1000) and its due date (in seconds; lower than 2×106).
Output
Sample Input
6
7 15
8 20
6 8
4 9
3 21
5 22
Sample Output
4
题解:贪心算法,首先按截至时间从小到大排序,这个比较自然,然后贪心加区间,如果能直接加进去,就先加进去,如果不能,就比较该区间的持续时间和目前算进答案的持续时间最长的区间,如果该区间持续时间短,就删去大的,加进小的,正确性还是比较明显的。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int maxn = 800000 + 100; 6 7 struct Work { 8 int q, d; 9 Work() {} 10 Work(int _q, int _d) : q(_q), d(_d) {} 11 bool operator < (const Work &a)const { 12 if (a.d == d) return q < a.q; 13 else return d < a.d; 14 } 15 }work[maxn]; 16 17 int n; 18 19 int main() 20 { 21 //freopen("input.txt", "r", stdin); 22 int iCase; 23 scanf("%d", &iCase); 24 bool flag = false; 25 while (iCase--) { 26 scanf("%d", &n); 27 if (flag) printf(" "); 28 flag = true; 29 int cnt = 0; 30 for (int i = 0; i < n; i++) { 31 scanf("%d %d", &work[i].q, &work[i].d); 32 } 33 34 sort(work, work + n); 35 int ans = 0, pos = 0; 36 priority_queue<int> que; 37 for (int i = 0; i < n; i++) { 38 if (pos + work[i].q <= work[i].d) { 39 pos += work[i].q; 40 que.push(work[i].q); 41 ans++; 42 } 43 else if(!que.empty()){ 44 int top = que.top(); 45 if (top > work[i].q) { 46 pos += work[i].q - top; 47 que.pop(); 48 que.push(work[i].q); 49 } 50 } 51 } 52 printf("%d ", ans); 53 } 54 return 0; 55 }
以上是关于UVA1153-Keep the Customer Satisfied(贪心)的主要内容,如果未能解决你的问题,请参考以下文章
UVa1153 Keep the Customer Satisfied (贪心,优先队列)
uva1153 Keep the Customer Satisfied
Uva 1153 Keep the Customer Satisfied (贪心+优先队列)