UVA 10313 Pay the Price

本文介绍了一种使用前缀和将动态规划算法的时间复杂度从O(n^3)优化到O(n^2)的方法,并通过具体代码示例展示了如何实现这一优化过程。

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

  算法:用前缀和把O(n^3)的dp优化成O(n^2)。注意:(1)long long。(2)L1、L2不一定在[1,300]内。(3)没有空行(不用处理空行能过)。

//10313 	Pay the Price 	Accepted 	C++ 	0.056 	2012-11-20 11:23:14
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 300+5;
const int MAX = 300;
int N, L1, L2;
long long d[MAXN][MAXN], f[MAXN][MAXN];
char line[100];
int main()
{
	d[0][0] = f[0][0] = 1;
	for (int i = 1; i <= MAX; i++)
		for (int j = 1; j <= i; j++)
		{
			d[i][j] = f[i-j][min(j, i-j)];
			f[i][j] = f[i][j-1]+d[i][j];
		}
	while (gets(line))
	{
		int n = sscanf(line, "%d%d%d", &N, &L1, &L2);
		if (n > 0)
		{
			if (n == 1)
				printf("%lld\n", f[N][N]);
			else if (n == 2)
				printf("%lld\n", f[N][min(L1, N)]);
			else if (L1 > N)
				printf("0\n");
			else if (L1 > 0)
				printf("%lld\n", f[N][min(L2, N)]-f[N][L1-1]);
			else
				printf("%lld\n", f[N][min(L2, N)]);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值