UVALive 4850 Installations Greedy

topic link 

meaning of the title

The engineer needs to install n services, of which service Ji requires si units of installation time, and the deadline is di. There will be a penalty value for the timeout. If the actual completion time is ci, the penalty value is max{0, ci-di}. Execute the task from time 0. What is the minimum sum of the penalty values ​​of the two services with the largest penalty value?

 

analyze

At first glance it might seem like a dichotomy, but it's not. To do it greedily, arrange tasks according to di from small to large. When di is equal, let the tasks with the short completion time be ranked first. This way of arranging tasks is better for a certain time, but it does not meet the requirements of the problem. So you need to pick a task from the front of the two maximum penalty values, put it in the back, and then update the answer.

 

 

#include<cstdio>  
#include<algorithm>  
using namespace std;  
#define maxn 510  
struct Task{  
    int s, d;  
    bool operator <(const Task t) const{  
        if(t.d == d)  
            return s < t.s;  
        else  
            return d < t.d;    
    }  
}T[maxn];  
int pos, n;  
  
int solve(int cur) {  
    int MAX1 = 0, MAX2 = 0, sum = 0;  
    for(int i = 0; i <= pos; i++) {  
        if(i == cur)  
            continue;     
        sum += T[i].s;  
        if(sum - T[i].d >= MAX2)   
            MAX2 = sum - T[i].d;  
        if(MAX2 > MAX1)  
            swap(MAX1,MAX2);  
    }  
  
    sum += T[cur].s;  
    if(sum - T[cur].d >= MAX2)  
        MAX2 = sum - T[cur].d;  
    if(MAX2 > MAX1)  
        swap(MAX1,MAX2);  
  
    for(int i = pos + 1; i < n; i++) {  
        sum += T[i].s;  
        if(sum - T[i].d >= MAX2)  
            MAX2 = sum - T[i].d;  
        if(MAX2 > MAX1)  
            swap(MAX1,MAX2);  
    }  
    return MAX2 + MAX1;  
}  
  
int main() {  
    int test;  
    scanf("%d",&test);  
    while(test--) {  
        scanf("%d",&n);  
        for(int i = 0; i < n; i++)  
            scanf("%d%d",&T[i].s, &T[i].d);  
        sort(T,T+n);  
  
        int cur = 0, MAX1 = 0, MAX2 = 0, t = 0;  
        for(int i = 0; i < n; i++) {  
            cur += T[i].s;  
            if(cur - T[i].d >= MAX2) {  
                MAX2 = cur - T[i].d;  
                pos = i;      
            }  
            if(MAX2 > MAX1)  
                swap(MAX1,MAX2);  
        }  
  
        int ans = MAX1 + MAX2;  
        for(int i = 0; i < pos; i++)  
            years = min(years,solve(i));  
        printf("%d\n",ans);  
    }  
    return 0;  
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727527&siteId=291194637