题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=12695
解析:https://apps.topcoder.com/wiki/display/tc/SRM+586
这道题目当时比赛的时候没有做出来,当时感觉是用dp做,不过还是太水了,完全不知道怎么搞,后来看别人代码发现都是基本都是用的排列组合原理做的,觉得自己真是太弱了,再看这题给出的解析,发现用dp其实也蛮简单,主要是要想到子问题该怎么划分,又怎样由子问题生成最后的解。
另外发现用递归来做dp比非递归的简单多了,用递归只需要按照正常的思路自顶向下,然后确定好递归结束条件就好了,用非递归要自底向上的搞,不太直观。
再接再励!
代码如下,给出了用数学排列组合及用dp两种方法解的代码:
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <climits>
#include <cmath>
using namespace std;
/************** Program Begin *********************/
static const int MOD = 1000000009;
long long dp[27][1001];
class StringWeightDiv2 {
public:
// Math
int countMinimums(int L) {
long long res = 1;
if (L <= 26) {
int t = 26;
for (int i = L; i > 0; i--) {
res *= t;
res %= MOD;
--t;
}
} else {
// 计算 26! * C(L-1, 25)
res = 26;
for (int i = L - 1; i > L - 26; i--) {
res *= i;
res %= MOD;
}
}
return static_cast<int>(res);
}
// Dynamic Programming
// a代表可以使用的字符的种类,L表示需要生成的字符串的长度
long long onceConsecutive(int a, int L)
{
long long & res = dp[a][L];
if (res == -1) {
if (L == 0) { // base case,L=0时,a=0, 1, a>1, 0
res = (a == 0);
} else if (a == 1) {
res = 1;
}
else {
// calculate the sum. (We need to use modular arithmetic)
res = 0;
// 做了一点改动,改为了i <= L-a+1而不是原来的i <= L,保证了a>=L
for (int i = 1; i <= L-a+1; i++) {
res += (a * onceConsecutive(a-1, L-i) ) % MOD;
}
res %= MOD;
}
}
return res;
}
int countMinimums2(int L)
{
memset(dp, -1, sizeof(dp));
long long res = 1;
if ( L <= 26 ) {
// The simple case:
//26 * 25 * 24 * ...
for (int i=0; i < L; i++) {
res = (res * (26 - i)) % MOD;
}
} else {
// each letter must appear at least once, all instances
// of each letter must be consecutive.
res = onceConsecutive(26, L); //Use the recurrence relation
}
return res;
}
};
/************** Program End ************************/