题目:http://community.topcoder.com/stat?c=problem_statement&pm=13063&rd=15958
想到O(N^3)的算法不难,空间上可以优化为O(N^2),因为k状态只与k-1状态有关,后来在这里发现利用期望的线性性质可以得到O(N^2)的算法,进而可以观察出答案是有规律可循的,得到O(N)算法,确实还需要多思考。
代码:
#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
/*************** Program Begin **********************/
const int MAX_N = 500;
double dp[MAX_N + 1][MAX_N / 2 + 1][MAX_N / 2 + 1];
class RedPaint {
public:
int N;
double rec(int k, int L, int R)
{
// 当前位置左边有L个cells已经painted, 右边R个,还可以走k步
// 返回此种情况下还可以paint多少个新的cells
if (k == 0) {
return 0;
}
double & res = dp[k][L][R];
if (res > -0.5) {
return res;
}
res = 0;
res += 1.0 / 2 * rec(k - 1, max(0, L - 1), min(MAX_N / 2, R + 1))
+ 1.0 / 2 * rec(k - 1, min(MAX_N / 2, L + 1), max(0, R - 1));
if (0 == L) {
res += 0.5;
}
if (0 == R) {
res += 0.5;
}
return res;
}
double expectedCells(int N) {
this->N = N;
for (int i = 0; i < MAX_N + 1; i++) {
for (int j = 0; j < MAX_N / 2 + 1; j++) {
for (int k = 0; k < MAX_N / 2 + 1; k++) {
dp[i][j][k] = -1;
}
}
}
return 1 + rec(N, 0, 0);
}
};
/************** Program End ************************/