1. 程式人生 > >hdu 1789 貪心 優先佇列

hdu 1789 貪心 優先佇列

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

題解:

一開始自己想到的也是貪心,但是沒想出思路。參考了別人的程式碼,寫出來了,思路是
先按照扣分從大到小排序,分數相同則按照截止日期從小到大排序。。

然後按順序,從截止日期開始往前找沒有佔用掉的時間。
如果找不到了,則加到罰分裡面。
另一種思路是優先佇列,先對pair排序,每一天最大的Score入隊,如果碰到相同的Deadline,則每次進行出隊操作,很妙的演算法。

程式碼:

#include <bits/stdc++.h>

using namespace std;
const int maxn=1000+10;

int use[maxn];
typedef pair<int,int> p;

bool cmp(p a,p b)
{
    if(a.second!=b.second)
     return a.second>b.second;
    else
     return a.first<b.first;
}

int main()
{
    int T;
    cin>>T;
    int n;
    while(T--)
    {
       p data[maxn];
       cin>>n;
       for(int i=0;i<n;i++)
          cin>>data[i].first;
       for(int i=0;i<n;i++)
          cin>>data[i].second;
       sort(data,data+n,cmp);
       int sum = 0,j;
       memset(use,0,sizeof(use));

       for(int i=0;i<n;i++)
       {
           for(j=data[i].first;j>0;j--)
           {
              if(!use[j])
              {
                  use[j] = 1;
                  break;
              }
           }
           if(j==0)
            sum+=data[i].second;
       }
       cout<<sum<<endl;
    }
    return 0;
}
#include <bits/stdc++.h>

using namespace std;
typedef pair<int,int> p;
const int maxn = 1000+10;



int main()
{
    int T;
    cin>>T;int n;
    p data[maxn];
    while(T--)
    {
       cin>>n;
       for(int i=0;i<n;i++)
         cin>>data[i].first;
       for(int i=0;i<n;i++)
        cin>>data[i].second;
        sort(data,data+n);

        int day=0,ans=0;
        priority_queue<int,vector<int>,greater<int> > pq;
        for(int i=0;i<n;i++)
        {
            pq.push(data[i].second);
            if(day<data[i].first)
            {
               day++;
               continue;
            }
            int tmp = pq.top();
            ans+=tmp;
            pq.pop();
        }
        cout<<ans<<endl;
    }
    return 0;
}