码迷,mamicode.com
首页 > 其他好文 > 详细

Supermarket

时间:2015-09-25 18:08:36      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Supermarket

Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

A supermarket has a set Prod of products on sale. It earns a profit px for each product x∈Prod sold by a deadline dx that is measured as an integral number of time units starting from the moment the sale begins. Each product takes precisely one unit of time for being sold. A selling schedule is an ordered subset of products Sell ≤ Prod such that the selling of each product x∈Sell, according to the ordering of Sell, completes before the deadline dx or just when dx expires. The profit of the selling schedule is Profit(Sell)=Σ x∈Sellpx. An optimal selling schedule is a schedule with a maximum profit. 
For example, consider the products Prod={a,b,c,d} with (pa,da)=(50,2), (pb,db)=(10,1), (pc,dc)=(20,2), and (pd,dd)=(30,1). The possible selling schedules are listed in table 1. For instance, the schedule Sell={d,a} shows that the selling of product d starts at time 0 and ends at time 1, while the selling of product a starts at time 1 and ends at time 2. Each of these products is sold by its deadline. Sell is the optimal schedule and its profit is 80. 
技术分享

Write a program that reads sets of products from an input text file and computes the profit of an optimal selling schedule for each set of products. 

Input

A set of products starts with an integer 0 <= n <= 10000, which is the number of products in the set, and continues with n pairs pi di of integers, 1 <= pi <= 10000 and 1 <= di <= 10000, that designate the profit and the selling deadline of the i-th product. White spaces can occur freely in input. Input data terminate with an end of file and are guaranteed correct.
并查集优化:
    首先了解p值越大,更应该卖出,所以我们可以考虑在最后时期 d值 时卖出,该时期如若已被其他物品占有,就往前搜索,找到空余的时间卖出。
    然后用并查集优化搜索过程,如若确定该时间被卖物品,构造树pre[x] = x - 1;这样通过find()就阔以快速地寻找到空余时间了。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int pre[10005];
struct node{
    int p,d;
    bool operator<(const node &x)const{
        return p > x.p;
    }
}a[10005];
void init(){
    for(int i = 1; i <= 10000; i++)
        pre[i] = i;
}
int find(int x){
    return pre[x] == x ? pre[x] : pre[x] = find(pre[x]);
}
int main(){
    int n;
    while(~scanf("%d",&n)){
        int ans = 0;
        init();
        for(int i = 0; i < n; i++){
            scanf("%d%d",&a[i].p,&a[i].d);
        }
        sort(a,a+n);
        for(int i = 0; i < n; i++){
            int fi = find(a[i].d);
            if(fi > 0){
                ans += a[i].p;
                pre[fi] = fi-1;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

Supermarket

标签:

原文地址:http://www.cnblogs.com/ACMessi/p/4838857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!