Supermarket POJ

超市里有N个商品. 第i个商品必须在保质期(第di天)之前卖掉, 若卖掉可让超市获得pi的利润. 
每天只能卖一个商品.
现在你要让超市获得最大的利润. 
(原题说明过于抽象)

Input

多组数据. 
每组数据第一行为N, 即超市的商品数目
之后N行数字. 第i行为 pi, di

Output

对于每一组数据, 输出当前条件下超市的最大利润

Sample Input

4 
50 2  
10 1   
20 2   
30 1

7  
20 1   
2 1   
10 3  
100 2   
8 2   
5 20  
50 10

Sample Output

80
185

这题数据水了

根据数据范围完全可以将暴力卡掉

并查集类似记忆化搜索

对于充分的操作只会执行一次

所以可以优化此题

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int father[100005];
pair<int,int>a[100005];
int fin(int x)
{
    if(father[x]==x) return x;
    return father[x]=fin(father[x]);
}
int cmp(pair<int,int>p ,pair<int,int> q)
{
    return p.first>q.first;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d",&a[i].first,&a[i].second);
    }
    for(int i=0;i<=100000;i++)
        father[i]=i;
    sort(a+1,a+1+n,cmp );
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        int tmp=fin(a[i].second);
        if(tmp==0)
            continue;
        else
        {
            father[tmp]=fin(tmp-1);
            ans+=a[i].first;
        }
    }
    printf("%d
",ans);
    }
}
原文地址:https://www.cnblogs.com/caowenbo/p/11852299.html