题解:P17590 Xterfusion

· · 题解

闲话

没看见 2\le n \le 1000,想 O(n) 贪心浪费 30 分钟。

题目思路

我们首先注意到 对于 100\% 的数据,2\le n\le 1000。

对于 2\le n \le 1000,O(n^2) 算法可以通过。 枚举步长 i:

定义:

$r[j]$:以 $j$ 开头,每次向右跳 $i$ 的最长连续 $X$ 序列长度;若 $s[j]=\texttt{.}$ 则 $r[j]=0$。 转移: 从左往右扫,求 $l$ 数组: 若 $j-2i<0$,则 $l[j]=1$; 否则 $l[j]=l[j-2i]+1$。 从右往左扫,求 $r$ 数组: 若 $j+i\ge n$,则 $r[j]=1$; 否则 $r[j]=r[j+i]+1$。 对于每个位置 $j$,当前步长 $i$ 下的答案为 $l[j]+r[j]-1$($j$ 被左右两段重复计数,减去 $1$)。 所有步长、所有位置取最大值,就是全局答案。 总复杂度:枚举步长 $O(n)$,每次两遍线性扫描 $O(n)$,总 $O(n^2)$。 ## 代码实现 仅供参考: ```cpp #include <bits/stdc++.h> #define endl '\n' using namespace std; typedef long long ll; const int maxn = 1010; int n; int ans = 0; int l[maxn], r[maxn]; string s; signed main () { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> s; for (int i = 1; i < n; i ++) { for (int j = 0; j < s.size(); j ++) { if (s[j] == '.') { l[j] = 0; } else { if (j - 2 * i < 0) { l[j] = 1; } else { l[j] = l[j - 2 * i] + 1; } } } for (int j = s.size() - 1; j >= 0; j --) { if (s[j] == '.') { r[j] = 0; } else { if (i + j >= n) { r[j] = 1; } else { r[j] = r[i + j] + 1; } } } for (int j = 0; j < s.size(); j ++) { if (s[j] == 'X') { ans = max(ans, l[j] + r[j] - 1); } } } cout << ans; return 0; } ```