首页 > 代码库 > UVa 10313 - Pay the Price

UVa 10313 - Pay the Price

题目:求一个整数的重复拆分,限制拆分数的个数。

分析:dp,二维多重背包。整数拆分就用背包。

            状态:设f(i,j)为j拆分成i个元素的拆法;

            转移:f(i,j)= sum(f(i-1,j-k),f(i-1,j-2k),...,f(i-1,j-mk)){ 其中,1 ≤ k ≤ j };

            因为输入格式WA好多次,强大的sscanf( ⊙ o ⊙ )啊!

说明:注意数据范围,使用long long防止溢出。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

long long F[303][303],S[303][303];

int main()
{
	for (int i = 0 ; i <= 300 ; ++ i)
	for (int j = 0 ; j <= 300 ; ++ j)
		F[i][j] = S[i][j] = 0LL;
	F[0][0] = 1LL;
	for (int i = 1 ; i <= 300 ; ++ i)
	for (int j = 1 ; j <= 300 ; ++ j)
	for (int k = i ; k <= 300 ; ++ k)
		F[j][k] += F[j-1][k-i];
	S[0][0] = 1LL;
	for (int i = 1 ; i <= 300 ; ++ i)
	for (int j = 0 ; j <= 300 ; ++ j)
		S[i][j] = S[i-1][j]+F[i][j];
	
	int  N,L1,L2;
	char buf[256];
	while (gets(buf)) {
		int n = sscanf(buf,"%d%d%d",&N,&L1,&L2);
		if (n > 1) {
			if (L1 > 300) L1 = 300;
			if (n > 2) {
				if (L2 > 300) L2 = 300;
				if (L1 > L2) cout << 0 << endl;
				else if (L1) 
					cout << S[L2][N] - S[L1-1][N] << endl;
				else cout << S[L2][N] << endl;
			}else cout << S[L1][N] << endl; 
		}else cout << S[N][N] << endl;
	}
	return 0;
}

UVa 10313 - Pay the Price