HDU 1458(Tax Avoidance)

题意:两种买卖股票的方式,一种是“先买先卖”,即先买入的股票先卖出;一种是“后买先卖”,即后买入的股票先卖出。判断使用哪种方式赚的钱最少(可以为负数),输出方式和赚的钱数。

方法:使用双端队列 deque,分别计算两种方式赚的钱数,输出较小的即可。

(题目的输出格式要求有问题,总是 Presentation Error,但是方法和答案是正确的)

#include <iostream>
#include <string>
#include <queue>
#include <algorithm>
#include <iomanip>
using namespace std;

struct share //股票
{
	__int64 num; //数量
	__int64 price; //价格
	share() {}
	share(__int64 num, __int64 price) :num(num), price(price) {}
};

int main()
{
	string s;
	while (cin >> s)
	{
		if (s == "#")
			break;

		deque<share> p, q; //双端队列,分别模拟"LBFS"和"FBFS"
		__int64 ans1 = 0, ans2 = 0; //"LBFS"的结果,"FBFS"的结果
		__int64 num, price;
		string c;
		while (cin >> c)
		{
			if (c == "E")
				break;

			if (c == "B") //买入
			{
				cin >> num >> price;
				p.push_back(share(num, price));
				q.push_back(share(num, price));
			}
			else //卖出
			{
				cin >> num >> price;

				ans1 += price * num;
				__int64 i = num;
				while (i > 0) //"LBFS"方式
				{
					__int64 j = p.back().num;
					__int64 k = p.back().price;
					p.pop_back();
					if (i >= j)
					{
						i -= j;
						ans1 -= j * k;
					}
					else
					{
						ans1 -= i * k;
						p.push_back(share(j - i, k));
						i = 0;
					}

				}

				ans2 += price * num;
				i = num;
				while (i > 0) //"FBFS"方式
				{
					__int64 j = q.front().num;
					__int64 k = q.front().price;
					q.pop_front();
					if (i >= j)
					{
						i -= j;
						ans2 -= j * k;
					}
					else
					{
						ans2 -= i * k;
						q.push_front(share(j - i, k));
						i = 0;
					}
				}
			}
		}

		cout << s << " ";
		if (ans1 > ans2)
			cout << "FBFS ";
		else
			cout << "LBFS ";
		cout << setw(9) << setfill(' ') << fixed << setprecision(2) << 0.01 * min(ans1, ans2) << endl;
	}
	return 0;
}
发布了325 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Intelligence1028/article/details/105436591
hdu