链接
http://acm.hdu.edu.cn/showproblem.php?pid=6438
题意
n个城市按顺序排列 你按顺序走不回头
每个城市有个商品价格
你到这个城市的操作有三种
买一个商品、卖一个商品、啥都不干
你一开始有无数多的钱
问你最多赚多少钱,赚最多的情况下最少交易多少次
题解
易知交易次数一定是偶数(一买一卖)
使用优先队列进行操作
直接上代码 具体解释暂时先缓一会
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<vector>
#define ll long long
using namespace std;
struct node{
ll num;
ll kind; // 0其实代表已经操作过了的 1代表还没有操作过
node(ll xx=0,ll yy=0) : num(xx),kind(yy) { }
};
struct cmp
{
bool operator()(node a,node b)
{
if (a.num==b.num) return a.kind>b.kind;
else return a.num>b.num;
}
}; // 价格越低越在前面 如果价格相同 0在前 1在后
ll T,tt,ans,cnt,n,x,i;
int main()
{
scanf("%lld",&T);
for (tt=1; tt<=T; tt++)
{
priority_queue<node,vector<node>,cmp> q;
ans=cnt=0;
scanf("%lld",&n);
for (i=1; i<=n; i++)
{
scanf("%lld",&x);
node tmp(x,1);
if (q.empty()) {
q.push(tmp);
continue;
}
node pre=q.top();
if (pre.num>=x) {
q.push(tmp);
continue;
} // 无法交易,所有之前的价格都比他高,那么这天只可能是卖出
ans+=x-pre.num;
if (pre.kind==1) cnt+=2;
q.pop();
q.push(tmp);
tmp.kind=0;
q.push(tmp);
}
printf("%lld %lld\n",ans,cnt);
}
}
/*
质疑 如果遇到差价更大的怎么办
因为有标记为0的,那么
day1 买,day2 卖,day2 买,day3 卖 这一系列操作 实际上就相当于 day1买 day3卖
操作数并没有增加 因为已经标记为0了 只有标记为1的时候才会加2
*/