HDU——Doing Homework Again(贪心算法)

Problem Description

Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test. And now we assume that doing everyone homework always takes one day. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.

Input

The input contains several test cases. The first line of the input is a single integer T that is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=1000) which indicate the number of homework.. Then 2 lines follow. The first line contains N integers that indicate the deadlines of the subjects, and the next line contains N integers that indicate the reduced scores.

Output

For each test case, you should output the smallest total reduced score, one line per test case.

Sample Input

3
3
3 3 3
10 5 1
3
1 3 1
6 2 3
7
1 4 6 4 2 4 3
3 2 1 7 6 5 4

Sample Output

0
3
5

解题思路:

因为每个作业花费的时间都是一天,所以现在只要考虑其截止日期和花费的分数。
首先排序,将花费分数多的排在前面,若花费的分数相同,则将截止日期较早的排在前面。
然后,从第一个开始,看看可不可以在他要求的截止日期之前找到没有被占用的一天来完成这个任务。

代码:

//贪心算法
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef struct{
    int deadline;
    int cost;
}Homework;

int used[1010];

bool method(Homework a , Homework b){
    if(a.cost != b.cost)
        return a.cost > b.cost;
    else
        return a.deadline < b.deadline;

}
Homework work[1010];

int main(){
    //freopen("D://testData//1789.txt" , "r" , stdin);
    int t;
    int n , i , j;
    scanf("%d" , &t);
    while(t --){
        scanf("%d" , &n);
        for(i = 0 ; i < n ; i ++)
            scanf("%d",&work[i].deadline);
        for(i = 0 ; i < n ; i ++)
            scanf("%d",&work[i].cost);

        sort(work , work + n , method);
        memset(used , 0 , sizeof(used));

        int cost = 0;

        for(i = 0 ; i < n ; i ++){
            for(j = work[i].deadline ; j > 0 ; j --){   //只要找到一个在截止日期之前的没有被占用的日期就说明这个作业可以完成
                if(used[j] == 0){
                    used[j] = 1;
                    break;
                }
            }
            if(j == 0){
                cost = cost + work[i].cost;
            }
        }
        printf("%d\n" , cost);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_38052999/article/details/80041805