首页 技术 正文
技术 2022年11月14日
0 收藏 581 点赞 3,726 浏览 1592 个字

有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 ;
}

代码君二

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,116
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,588
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,433
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,204
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,840
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,925