Codeforces Round #494 (Div. 3) F. Abbreviation
阿新 • • 發佈:2018-07-13
bre lse 思路 -- end cpp space back 匹配
題目大意
- 在一些字符串中找到幾個(大於等於2個)不相交的區間,且這些區間都相等,即區間內字符串都相等。
解題思路
- 我們可以用遞推的方式求出f[i][j]表示以i,j為結束,已經匹配了多長的字符串。
- 求出f之後,枚舉區間,計算匹配次數,得出結果。
代碼
#include <bits/stdc++.h> using namespace std; vector<string> a; int n; int dp[350][350]; int main() { int totl = 0; /*總長度*/ cin >> n; for (int i = 0; i < n; i++) { string t; cin >> t; a.push_back(t); totl += t.size(); } totl += n - 1; // 計算dp for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (a[i] == a[j]) { if (i == 0) dp[i][j] = 1; else dp[i][j] = dp[i - 1][j - 1] + 1; } else dp[i][j] = 0; } } int ans = totl; for (int i = n - 1; i >= 0; i--) { int sum = 0; /*匹配長度為d*/ for (int d = 1; i - d >= 0; d++) { sum += a[i - d + 1].size(); int cnt = 0; /*匹配次數*/ for (int j = i - d; j >= 0; ) { if (dp[j][i] >= d) { cnt++; j -= d; } else j--; } if (cnt) { cnt++; /*加上自己*/ int tmp = totl - cnt * sum + cnt; if (tmp < ans) ans = tmp; } } } cout << ans << endl; return 0; }
Codeforces Round #494 (Div. 3) F. Abbreviation