洛谷 P6125 [JSOI2009] 有趣的游戏

洛谷传送门

思路

考虑建出 AC 自动机之后 dp。对于每一个人分别计算它的胜率,设当前计算到第 \(i\) 个人的胜率,设 \(f_u\) 表示当前在 AC 自动机上的 \(u\) 号结点获胜的概率,对 AC 自动机上每个结点 \(u\) 写出它的转移方程:

  • \(u\) 为第 \(i\) 个字符串的叶子结点,\(f_u = 1\)

  • \(u\) 为叶子结点但 \(u\) 不为第 \(i\) 个字符串的叶子结点,\(f_u = 0\)

  • \(u\) 不为叶子结点,\(f_u = \sum\limits_{i=0}^m f_{ch_{u,i}} \times \dfrac{p_i}{q_i}\)

答案即为 \(f_0\)

发现这个转移是有环的,不能直接转移,因此高斯消元后得出答案。

时间复杂度 \(O(n^2ml + n^4l^3)\)

代码

code
/*

p_b_p_b txdy
AThousandSuns txdy
Wu_Ren txdy
Appleblue17 txdy

*/

#include <bits/stdc++.h>
#define pb push_back
#define fst first
#define scd second
#define mems(a, x) memset((a), (x), sizeof(a))

using namespace std;
typedef long long ll;
typedef long double ldb;
typedef pair<ll, ll> pii;

const int maxn = 110;
const ldb EPS = 1e-8;

int n, m, K;
ldb a[maxn][maxn], p[maxn];
char s[maxn];

struct AC {
	int tot, ch[maxn][15], fail[maxn], idx[maxn];
	
	void insert(char *s, int id) {
		int p = 0;
		for (int i = 0; s[i]; ++i) {
			if (!ch[p][s[i] - 'A']) {
				ch[p][s[i] - 'A'] = ++tot;
			}
			p = ch[p][s[i] - 'A'];
		}
		idx[p] = id;
	}
	
	void build() {
		queue<int> q;
		for (int i = 0; i < m; ++i) {
			if (ch[0][i]) {
				q.push(ch[0][i]);
			}
		}
		while (q.size()) {
			int u = q.front();
			q.pop();
			for (int i = 0; i < m; ++i) {
				if (ch[u][i]) {
					fail[ch[u][i]] = ch[fail[u]][i];
					q.push(ch[u][i]);
				} else {
					ch[u][i] = ch[fail[u]][i];
				}
			}
		}
	}
} ac;

void gauss() {
	for (int i = 0; i <= ac.tot; ++i) {
		int r = -1;
		for (int j = i; j <= ac.tot; ++j) {
			if (fabs(a[i][j]) > EPS) {
				r = j;
				break;
			}
		}
		if (r == -1) {
			continue;
		}
		for (int j = i; j <= ac.tot + 1; ++j) {
			swap(a[i][j], a[r][j]);
		}
		for (int j = i + 1; j <= ac.tot + 1; ++j) {
			a[i][j] /= a[i][i];
		}
		a[i][i] = 1;
		for (int j = 0; j <= ac.tot; ++j) {
			if (i == j) {
				continue;
			}
			for (int k = i + 1; k <= ac.tot + 1; ++k) {
				a[j][k] -= a[j][i] * a[i][k];
			}
			a[j][i] = 0;
		}
	}
}

void solve() {
	scanf("%d%d%d", &n, &K, &m);
	for (int i = 0, x, y; i < m; ++i) {
		scanf("%d%d", &x, &y);
		p[i] = 1. * x / y;
	}
	for (int i = 1; i <= n; ++i) {
		scanf("%s", s);
		ac.insert(s, i);
	}
	ac.build();
	for (int i = 1; i <= n; ++i) {
		for (int j = 0; j <= ac.tot; ++j) {
			for (int k = 0; k <= ac.tot + 1; ++k) {
				a[j][k] = 0;
			}
		}
		for (int u = 0; u <= ac.tot; ++u) {
			if (ac.idx[u] == i) {
				a[u][u] = 1;
				a[u][ac.tot + 1] = 1;
			} else if (ac.idx[u]) {
				a[u][u] = 1;
				a[u][ac.tot + 1] = 0;
			} else {
				a[u][u] = 1;
				for (int j = 0; j < m; ++j) {
					a[u][ac.ch[u][j]] -= p[j];
				}
			}
		}
		gauss();
		printf("%.2Lf\n", a[0][ac.tot + 1]);
	}
}

int main() {
	int T = 1;
	// scanf("%d", &T);
	while (T--) {
		solve();
	}
	return 0;
}
posted @ 2022-07-18 16:17  zltzlt  阅读(59)  评论(0编辑  收藏  举报