Greedy?(贪心)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuewenyao/article/details/89005320

原文

iSea is going to be CRAZY! Recently, he was assigned a lot of works to do, so many that you can't imagine. Each task costs Ci time as least, and the worst news is, he must do this work no later than time Di! 
OMG, how could it be conceivable! After simple estimation, he discovers a fact that if a work is finished after Di, says Ti, he will get a penalty Ti - Di. Though it may be impossible for him to finish every task before its deadline, he wants the maximum penalty of all the tasks to be as small as possible. He can finish those tasks at any order, and once a task begins, it can't be interrupted. All tasks should begin at integral times, and time begins from 0. 

Input

The first line contains a single integer T, indicating the number of test cases. 
Each test case includes an integer N. Then N lines following, each line contains two integers Ci and Di. 

Technical Specification 
1. 1 <= T <= 100 
2. 1 <= N <= 100 000 
3. 1 <= Ci, Di <= 1 000 000 000 

Output

For each test case, output the case number first, then the smallest maximum penalty.

Sample Input

2
2
3 4
2 2
4
3 6
2 7
4 5
3 9

Sample Output

Case 1: 1
Case 2: 3

题解:这是一个明显的贪心,题目要求大的是总罚最小的情况下的最大的罚值,要是想让罚值最小,我们将戒指日期早的先做。我们对于两个相邻的作业,交换这两个作业的顺序,对于这个顺序的其他几个部分没有影响,那么我们要对这两个作业来进行一个排序。很显然我们要先做截止日期更早的是最优解,因为截止日期早的从后边换到前边,就不会增加多扣分了,所以将所有的交换后实际上就是截止日期的一个排序。

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1e5+5;
#define ll long long
struct node{
  int x , y;
}a[maxn];
int t , n , cas;
ll sum , ma;
bool cmp(node a , node b)
{
  return a.y < b.y;
}

int main()
{
    scanf("%d",&t);
          cas = 0;
    while(t--)
    {
      memset(a,0,sizeof(a));
      scanf("%d",&n);
      for(int i = 0 ; i < n ; i ++)
      {
        scanf("%d%d",&a[i].x,&a[i].y);
      }
      cas ++;
      sort(a , a+n , cmp);
      sum = 0 ;
      ma = 0;
      for(int i = 0 ; i < n ; i ++)
      {
        sum += a[i].x;
        ma = max(ma,sum-a[i].y);
      }
      printf("Case %d: %d\n",cas,ma);
    }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/yuewenyao/article/details/89005320