有n件商品,每件商品有它的利润和售出的最后期限,问能够得到的最大利润是多少
这道题和 HDU 1789 Doing Homework again 几乎一模一样,只不过这个是求最的扣分,本题是求最大利润
朴素的做法是:
按照每件商品的利润从大到小排序,有一个busy数组记录那天是否有东西卖出。对于每件商品,从它的截止日期开始遍历,如果那天有东西卖就看看前一天是否有卖东西,直到有一天没有东西卖或者前面的天数都有卖的。
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int maxn = + ;
struct Product
{
int p, d;
bool operator< (const Product& a) const
{
return p > a.p || (p == a.p && d > a.d);
}
}products[maxn];
bool busy[maxn]; int main(void)
{
#ifdef LOCAL
freopen("1456in.txt", "r", stdin);
#endif int n;
while(scanf("%d", &n) == )
{
memset(busy, false, sizeof(busy));
for(int i = ; i < n; ++i)
scanf("%d%d", &products[i].p, &products[i].d);
sort(products, products + n); int ans = ;
for(int i = ; i < n; ++i)
{
for(int j = products[i].d; j > ; --j)
{
if(!busy[j])
{
ans += products[i].p;
busy[j] = true;
break;
}
}
}
printf("%d\n", ans);
}
return ;
}
代码君一
并查集优化:
这里parent数组相当于之前代码的busy数组的优化。因为对于第i件商品我们都要从它的期限往前遍历来找到不忙的那天来卖,parent[i]存放第i天最近的能卖物品的天数。
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int maxn = + ;
struct Product
{
int p, d;
bool operator< (const Product& a) const
{
return p > a.p || (p == a.p && d > a.d);
}
}products[maxn];
int parent[maxn]; int Find(int a)
{
return parent[a] == a ? a : parent[a] = Find(parent[a]);
} int main(void)
{
#ifdef LOCAL
freopen("1456in.txt", "r", stdin);
#endif int n, maxday;
while(scanf("%d", &n) == )
{
maxday = ;
for(int i = ; i < n; ++i)
{
scanf("%d%d", &products[i].p, &products[i].d);
if(products[i].d > maxday) maxday = products[i].d;
} sort(products, products + n); int ans = ;
for(int i = ; i <= maxday; ++i)
parent[i] = i;
for(int i = ; i < n; ++i)
{
int pi = Find(products[i].d);
if(pi > )
{
parent[pi] = Find(pi - );
ans += products[i].p;
}
}
printf("%d\n", ans);
}
return ;
}
代码君二