Educational Codeforces Round 111 (Rated for Div. 2) E. Stringforces 二分答案+状压dp
Posted kaka0010
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Educational Codeforces Round 111 (Rated for Div. 2) E. Stringforces 二分答案+状压dp相关的知识,希望对你有一定的参考价值。
原题链接:https://codeforces.ml/contest/1550/problem/E
题意
有一个字符串由k个字符组成’?'可以填任意字符,字符有一个权值为 f i fi fi表示最长连续相同子串的长度,问所有字符中最小的 f i fi fi最大可以是多少。
分析
看到 M a x ( ∑ M i n Max(\\sum Min Max(∑Min)问题,最自然想到二分答案,先确定一个长度,然后去填数,判断是否可以满足。
首先初步的构想就是这样,然后考虑优化。如果直接暴力去填数,每个位置都要枚举k种情况,也就是 2 k n l o g n 2^knlogn 2knlogn的复杂度,那么我们想如果可以直接预处理出某个位置完成填数的最近距离,然后再用状压DP去跑是不是就可以了。
于是先预处理一个数组
f
[
i
]
[
j
]
f[i][j]
f[i][j]代表第i个字符从第j个位置开始,最先完成填数的位置,这个我们倒着跑一遍就可以了。然后状压处理起来就简单了,我们用dp[i]表示处理完当前字符的最近位置,转移方程就是
d
p
[
i
∣
(
1
<
<
j
)
]
=
m
i
n
(
d
p
[
i
∣
(
1
<
<
j
)
]
,
f
[
j
]
[
d
p
[
i
]
)
dp[i|(1<<j)]=min(dp[i|(1<<j)], f[j][dp[i])
dp[i∣(1<<j)]=min(dp[i∣(1<<j)],f[j][dp[i])
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll INF = 1e18;
const int N = 2e5 + 10;
const int M = 1e6 + 10;
const int MOD = 1e9 + 7;
char s[N];
int dp[1<<17];
int f[20][N], n, k;
bool check(int x) {
memset(dp, 0x3f, sizeof dp);
memset(f, 0x3f, sizeof f);
for (int i = 0; i < k; i++) {
int now = 0;
for (int j = n; j >= 1; j--) {
if (s[j] == '?' || s[j] == 'a' + i) now++;
else now = 0;
if (now >= x) f[i][j] = j + x;
else f[i][j] = f[i][j+1];
}
}
dp[0] = 1;
for (int i = 0; i < 1 << k; i++) {
for (int j = 0; j < k; j++) {
if (i >> j & 1) continue;
int state = i | (1 << j);
if (dp[i] <= n + 1) dp[state] = min(dp[state], f[j][dp[i]]);
}
}
if (dp[(1<<k)-1] > n + 1) return false;
else return true;
}
void solve() {
cin >> n >> k;
cin >> (s + 1);
int l = 0, r = n;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) l = mid + 1;
else r = mid - 1;
}
cout << r << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
signed test_index_for_debug = 1;
char acm_local_for_debug = 0;
do {
if (acm_local_for_debug == '$') exit(0);
if (test_index_for_debug > 20)
throw runtime_error("Check the stdin!!!");
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
} while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
solve();
#endif
return 0;
}
以上是关于Educational Codeforces Round 111 (Rated for Div. 2) E. Stringforces 二分答案+状压dp的主要内容,如果未能解决你的问题,请参考以下文章
Educational Codeforces Round 7 A
Educational Codeforces Round 7
Educational Codeforces Round 90
Educational Codeforces Round 33