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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章