SRM 607 D1 L1:PalindromicSubstringsDiv1,DP

题目:http://community.topcoder.com/stat?c=problem_statement&pm=12964


需要用到概率论中求期望的数学公式:若 随机变量 X = X1 + X2 + ... + Xn,则 E(X) = E(X1) + E(X2) + ... + E(Xn)。

代码:

#include <algorithm>
#include <iostream>
#include <sstream>

#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>

using namespace std;


#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)

/*************** Program Begin **********************/
double dp[5001][5001];

class PalindromicSubstringsDiv1 {
public:
    double expectedPalindromes(vector <string> S1, vector <string> S2) {
        double res = 0;
	memset(dp, 0, sizeof(dp));
	string S;
	for (int i = 0; i < S1.size(); i++) {
		S += S1[i];
	}
	for (int i = 0; i < S2.size(); i++) {
		S += S2[i];
	}
	int N = S.size();
	for (int i = 0; i < N; i++) {
		dp[i][i] = 1.0;
		res += 1.0;
	}
	for (int len = 2; len <= N; len++) {
		for (int i = 0; i <= N - len; i++) {
			int marks = 0;
			if (S[i] == '?') {
				++marks;
			}
			if (S[i + len - 1] == '?') {
				++marks;
			}
			if (2 == len) {
				if (0 == marks && S[i] == S[i + len - 1]) {
					dp[i][i + len - 1] = 1.0;
				} else if (0 != marks) {
					dp[i][i + len - 1] = 1.0 / 26.0;
				}
			} else {
				if (0 == marks && S[i] == S[i + len - 1]) {
					dp[i][i + len - 1] = dp[i+1][i + len - 2];					
				} else if (0 != marks) {
					dp[i][i + len - 1] = (1.0 / 26.0) * dp[i+1][i + len - 2];
				}
			}
			res += dp[i][i + len - 1];
		}
	}
        return res;
    }

};

/************** Program End ************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值