USACO Buy Low, Buy Lower 解题报告

本文介绍了一种求解最长递减子序列及其不同序列数量的方法,通过动态规划实现,考虑了序列值相同时的特殊情况,并提供了一个C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题前部分是求最长递减子序列,后部分是求不同的最长递减子序列的个数。前者利用二分查找有O(nlogn)的时间复杂度,但由于后者决定了整体的时间复杂度,故这里没有采用这样的优化。后者如果不考虑“不同”,则为简单的动态规划,把在这个元素之前能够“续”一个的序列数目加起来就可以。当考虑“不同”的时候需要仔细考虑下,实际上,假设以当前元素结束的最长递减子序列长度为pos,那么之前所有与该元素具有相同pos的元素,如果值相同,应该是连续出现的,即中间不会有个元素值不同。考虑下pos为以当前元素结束的最长递减子序列长度可以立刻得出这样的结论。这也是标准答案采用的方法。

/* 
ID: thestor1 
LANG: C++ 
TASK: buylow 
*/
#include <iostream>  
#include <cmath>  
#include <cstdio>  
#include <cstring>  
#include <climits>  
#include <cassert>  
#include <string>  
#include <vector>  
#include <set>
#include <map>  
#include <queue>  
#include <stack>  
#include <algorithm>

using namespace std;

string sum_str(string str1, string str2)
{
	string ret(max(str1.size(), str2.size()), '0');
	int i = str1.size() - 1, j = str2.size() - 1, k = ret.size() - 1, carry = 0, sum = 0;
	while (i >= 0 && j >= 0)
	{
		sum = carry + str1[i] - '0' + str2[j] - '0';
		ret[k] = (sum % 10) + '0';
		carry = sum / 10;
		i--;
		j--;
		k--;
	}

	while (i >= 0)
	{
		sum = carry + str1[i] - '0';
		ret[k] = (sum % 10) + '0';
		carry = sum / 10;
		i--;
		k--;
	}

	while (j >= 0)
	{
		sum = carry + str2[j] - '0';
		ret[k] = (sum % 10) + '0';
		carry = sum / 10;
		j--;
		k--;
	}

	assert(k == -1);

	if (carry)
	{
		ret = "1" + ret;
	}

	return ret;
}

int main()
{
	sum_str("16", "4");
	FILE *fin  = fopen("buylow.in", "r");
	FILE *fout = fopen("buylow.out", "w");
	
	int N;
	fscanf(fin, "%d", &N);
	std::vector<int> prices;
	for (int i = 0; i < N; ++i)
	{
		int p;
		fscanf(fin, "%d", &p);
		prices.push_back(p);
	}

	int L = 0;
	std::vector<int> pos(N, 1);
	for (int i = 0; i < N; ++i)
	{
		for (int j = 0; j < i; ++j)
		{
			if (prices[j] > prices[i])
			{
				if (pos[j] + 1 > pos[i])
				{
					pos[i] = pos[j] + 1;
				}
			}
		}

		if (pos[i] > L)
		{
			L = pos[i];
		}
	}

	// cout<<"L:"<<L<<endl;
	string sum = "0";
	std::vector<string> cnt(N, "1");

	for (int i = 0; i < N; ++i)
	{
		if (pos[i] != 1)
		{
			cnt[i] = "0";
		}

		for (int j = 0; j < i; ++j)
		{
			if (prices[j] > prices[i] && pos[j] + 1 == pos[i])
			{
				// cout<<"[debug]"<<cnt[i]<<"+"<<cnt[j]<<"=";
				cnt[i] = sum_str(cnt[i], cnt[j]);
				// cout<<"[debug]"<<cnt[i]<<endl;
			}

			if (prices[j] == prices[i] && pos[j] < pos[i])
			{
				cnt[j] = "0";
			}
			else if (prices[j] == prices[i] && pos[j] == pos[i])
			{
				cnt[i] = "0";
			}
		}

		if (pos[i] == L)
		{
			sum = sum_str(sum, cnt[i]);
		}
	}

	cout<<"sum:"<<sum<<endl;
	fprintf(fout, "%d %s\n", L, sum.c_str());

	fclose(fin);
	fclose(fout);
	return 0;  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值