POJ - 1456 Supermarket (排序+贪心)

超市里有N个商品. 第i个商品必须在保质期(第di天)之前卖掉, 若卖掉可让超市获得pi的利润.
每天只能卖一个商品.
现在你要让超市获得最大的利润.
Input
多组数据.
每组数据第一行为一个整数N (0 <= N <= 10000), 即超市的商品数目
之后N行各有两个整数, 第i行为 pi, di (1 <= pi, di <= 10000)
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
Hint
Translated by shleodai
问题链接: http://poj.org/problem?id=1456
问题简述: 中文题意
问题分析: 用结构体存下每种菜的价格跟过期天数,然后根据价格进行排序,把商品从贵到便宜扫一遍,判断它能否在快过期那天卖出去,把这天标记,如果这天不能卖出去就往他过期天数前面扫,找到能卖出去的那天,这样保证能够得出最优解。
AC通过的C++语言程序如下:

#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include<vector>
#define ll long long
using namespace std;

bool vis[100005];

struct goods
{
    ll value;
    int day;
}a[100005];

bool cmp(goods x, goods y)
{
    return x.value>y.value;
}

int main()
{
    ios::sync_with_stdio(false);
    int n;
    while(cin>>n)
    {
        int maxnd=-1;
        for(int i=0;i<n;i++)
        {
            cin>>a[i].value>>a[i].day;
            maxnd=max(a[i].day,maxnd);
        }
        sort(a,a+n,cmp);
        ll ans=0;
        for(int i=0;i<n;i++)
        {
            if(!vis[a[i].day])
            {
                ans+=a[i].value;
                vis[a[i].day]=1;
            }
            else
            {
                for(int j=a[i].day-1;j>0;j--)
                {
                    if(!vis[j])
                    {
                        ans+=a[i].value;
                        vis[j]=1;
                        break;
                    }
                }
            }
        }
        cout<<ans<<endl;
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44012745/article/details/89452026