贪心,并查集——POJ-1456

题目含义

有一堆商品,给出了售货截止日期和售价

让你选择每天售出的商品,使得收入最大

题目分析

为什么可以选择并查集呢,我一开始也不明白

但是尽量选择售价高的商品,这个贪心思维是没问题的

主要在于选择一个商品后,可能一些快到期的商品就不能选了

在这里,我们根据截止日期分堆,一个截止日期一个集合

我们选择一个最大价值商品,最优的情况是在它的截止日期售出

但售出后,跟它同日期的商品就不能在这天售出

于是便将他们融入前一天的集合中,找出前一天能最晚售出价值最高的商品

这就是贪心策略了,不过用到了并查集的方法

题目代码

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e4+7;
int f[maxn],n;
struct node{
    int p,d;
}day[maxn];
int get(int x){
    if(f[x]==-1)return x;
    else return f[x]=get(f[x]);
}
bool cmp(node a,node b){
    if(a.p!=b.p)return a.p>b.p;
    return a.d<b.d;
}
int main(){
    while(~scanf("%d",&n)){
        for(int i=1;i<=n;i++)
            scanf("%d%d",&day[i].p,&day[i].d);
        sort(day+1,day+1+n,cmp);
        memset(f,-1,sizeof(f));
        int ans=0;
        for(int i=1;i<=n;i++){
            int t=get(day[i].d);
            if(t>0){
                ans+=day[i].p;
                f[t]=t-1;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/helman/p/11234046.html