Greedy, disjoint-set --POJ-1456

Title meaning

There are a bunch of merchandise, it gives the sales cut-off date and price

Allows you to choose the goods sold every day, making the maximum income

Topic analysis

Why you can choose disjoint-set it, I do not understand the beginning

But try to choose high-priced goods, the greedy thinking is not the problem

The main is to choose a commodity, the commodity may be some expiring can not be elected

Here, we divide the heap to a deadline, a deadline for a collection

We chose a maximum value of goods, the best situation is at its deadline sold

However, after the sale, saying the same date the goods can not be sold on this day

So we put them into the collection of the previous day, the first day to find out the latest sale of the highest value of goods

This is the greedy strategy, but used the method of disjoint-set

Topic Code

#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;
}

 

Guess you like

Origin www.cnblogs.com/helman/p/11234046.html