hdu 3689

2260 단어
kmp에 dp 추가
dp[i][j]는 총 길이가 i이고 끝의 꼬리의 길이가 j인 확률을 나타낸다(끝의 꼬리의 길이가 j인 것은 단어의 길이가 j인 접두사가 끝에 있음을 나타낸다)
그러면 dp[i][j]--->dp[i+1][s],s는 kmp로 구한다.
마지막 통계 답안
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1007;
const double eps = 1e-10;
double ans;
double dp[maxn][20];
double p[maxn];
int n, m;
int next[maxn];
char str[maxn];
vector<char> letter;
void getNext() {
    int k = 0;
    next[0] = 0;
    int len = strlen(str);
    for (int i = 1; i < len; i++) {
        while (k  && str[i] != str[k]) {
            k = next[k - 1];
        }
        if (str[i] == str[k]) {
            k++;
        }
        next[i] = k;
    }
}
int main() {
//    freopen("in.txt", "r", stdin);
    while (scanf("%d%d", &n, &m) != EOF) {
        if (!n && !m) {
            break;
        }
        letter.clear();
        for (int i = 1; i <= n; i++) {
            char c[10];
            double cnt_p;
            scanf("%s%lf", c, &cnt_p);
            p[c[0] - 'a'] = cnt_p;
            letter.push_back(c[0]);
        }
        scanf("%s", str);
        getNext();
        memset(dp, 0, sizeof(dp));
        dp[0][0] = 100.0;
        int len = strlen(str);
        double ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < len; j++) {
                if (fabs(dp[i][j]) > eps) {
                    for (int k = 0; k < n; k++) {
                        char cnt_c = letter[k];
                        int cnt_loc = j;
                        while (cnt_loc && cnt_c != str[cnt_loc]) {
                            cnt_loc = next[cnt_loc - 1];
                        }
                        if (cnt_c == str[cnt_loc]) {
                            cnt_loc++;
                        }
                        dp[i + 1][cnt_loc] += dp[i][j] * p[cnt_c - 'a'];

                    }
                }
            }
        }
        for (int i = 0; i <= m; i++) {
            ans += dp[i][len];
        }
        printf("%.2f%%
", ans); } return 0; }

좋은 웹페이지 즐겨찾기