POJ-1456 Suprmarket (disjoint-set greedy +)

Topic links:
https://cn.vjudge.net/problem/POJ-1456

Subject to the effect:
there are N goods, each shelf-life is di, obtained income is pi, ask the maximum benefit that can be sold is the number of
multiple sets of test samples

Problem solution ideas:
At first glance, the question is not that greedy it? Optimal strategies are sold in the last day shelf life, elect to sell the highest income, then the sum is not on the list thing? However, this is completely wrong! Do not be thinking! If this sample
3115232 What is the answer? It is 8! Because the next day to see the highest return is 5, but 3 gains can sell on the first day!

Disjoint-set array f [i] specified:
1. f [i] = -. 1 i-th day are not selling, the lookup returns i
2. f [i] =. 1-i i-th day of what has been sold , the next day i shelf life of only the first day sold i-1, when looking return Find (F [i-1])

Therefore , problem-solving ideas probably came out, first of all revenue commodity descending row, then find and check of arrays,
if greater than 0, then sell.

Code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int MAX=-99999;
int f[10011];//并查集数组

struct G
{//商品结构体
    int p,d;//p代表收益,d代表保质期
}goods[10011];

int Find(int x)
{//查找
    if(f[x]==-1)
        return x;
    return Find(f[x]);
}

bool cmp(G g1,G g2)
{
    return g1.p>g2.p;
}
int main()
{
    int n,t;
    while(scanf("%d",&n)!=EOF)
    {
        memset(f,-1,sizeof(f));
        int sum=0;
        memset(goods,0,sizeof(goods));
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&goods[i].p,&goods[i].d);
        }
        sort(goods,goods+n,cmp);
        for(int i=0;i<n;i++)
        {
            t=Find(goods[i].d);
            if(t>0)
            {
                sum+=goods[i].p;
                f[t]=t-1;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

Published 67 original articles · won praise 42 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_26235879/article/details/98958751