51Nod 1163 最高的獎勵 貪心

思路1:

這個是非常好的一道貪心題目!

每個任務有一個最晚完成時間,用一個隊列來維護到當前時間t的時候,一共完成了哪些任務。 遇到最晚完成時間大於t的,直接加入隊列,與t相等的話,則置換一下,使得隊列裏面的值最大。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node {
    int e;
    ll w;
    node ( int _e,ll _w ) {
        e = _e;
        w = _w;
    }
    bool operator < ( const node & a ) const  {
        return w>a.w;
    }
};

bool cmp( const node &a,const node &b ) {
    return a.e<b.e;
}
vector<node> vec;
int main() {
    int n;
    int m=0;
    int e,w;
    cin>>n;
    for ( int i=0; i<n; i++ ) {
        scanf("%d%d",&e,&w);
        vec.push_back( node(e,w) ) ;
    }
    sort( vec.begin() ,vec.end(),cmp );
    priority_queue<node> que;
    int time = 1;
    for ( int i=0; i<vec.size(); i++ ) {
        if ( vec[i].e>=time ) {
            que.push( vec[i] ) ;
            time++;
        } else {
            if ( vec[i].w > que.top().w ) {
                que.pop();
                que.push( vec[i] );
            }
        }
    }
    ll ans = 0 ;
    while ( que.empty()==0 ) {
        ans += que.top().w;
        que.pop();
    }
    cout<<ans<<endl;
    return 0 ;
}


思路2:

這個思路我有想過,但是一直n2的複雜度,沒想到可以用類似並查集的思想實現。

可以根據獎勵的大小排序。

f[i] = j 代表 最晚完成時間可以在1-j時間內完成。

當我們選定過了一個活動,一定要從j到1進行賦值,不能搶佔前面的時間。

#include <bits/stdc++.h>
using namespace std;
const int N = 50000+100;
struct node {
    int cost;
    int time;
    node(){};
    node ( int _c,int _t) { cost = _c; time = _t; };
};
int f[N];
node nodes[N];
int getTime( int x )  {
    if ( x==0 ) return 0;
    else if ( f[x]==x ) {
        f[x] = x-1;
        return x;
    } else {
        return f[x] = getTime( f[x] );
    }
}
bool cmp( const node &a,const node &b ) {
    if ( a.cost!=b.cost )
        return a.cost>b.cost;
    else
        return a.time<b.time;
}
int main()
{
    int n;
    scanf("%d",&n);
    for ( int i=1; i<=n; i++ )
        scanf("%d%d",&nodes[i].time,&nodes[i].cost),f[i]=i;
    sort( nodes+1,nodes+1+n,cmp );
    long long ans =0 ;
    for ( int i=1; i<=n ; i++ ) {
        if ( getTime( nodes[i].time ) >0 )
            ans += nodes[i].cost;
    }
    cout<<ans<<endl ;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章