题目: http://community.topcoder.com/stat?c=problem_statement&pm=13092&rd=15848
参考: http://apps.topcoder.com/wiki/display/tc/SRM+615?decorator=printable
将题目条件转化为括号表达式模型就好做了.
代码:
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;
#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair
#define FOREACH(it, X) for(__typeof((X).begin()) it = (X).begin(); it != (X).end(); ++it)
/*************** Program Begin **********************/
const int MOD = 1000000007;
const int MAX_N = 5001;
const int MAX_M = 51;
long long dp[MAX_N][MAX_M][MAX_M];
class AlternativePiles {
public:
string C;
int M;
long long rec(int cur, int balance, int matches)
{
long long & res = dp[cur][balance][matches];
if (-1 != res) {
return res;
}
if (cur == C.size()) { // base case
if (0 == balance && 0 == matches) {
res = 1;
return res;
} else {
res = 0;
return res;
}
}
res = 0;
char x = C[cur];
if ('R' == x || 'W' == x) {
if (balance < M) {
res += rec(cur + 1, balance + 1, matches);
}
}
if ('G' == x || 'W' == x) {
if (balance > 0) {
res += rec(cur + 1, balance - 1, (matches + 1) % M);
}
}
if ('B' == x || 'W' == x) {
res += rec(cur + 1, balance, matches);
}
res %= MOD;
return res;
}
int count(string C, int M) {
int res = 0;
this->C = C;
this->M = M;
memset(dp, -1, sizeof(dp));
res = rec(0, 0, 0);
return res;
}
};
/************** Program End ************************/