思路:
kmp + 二分。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 const int MAXN = 2105; 7 int neXt[MAXN]; 8 9 void getNext(string s) 10 { 11 int n = s.length(); 12 neXt[0] = -1; 13 int k = -1, j = 0; 14 while (j < n) 15 { 16 if (k == -1 || s[j] == s[k]) 17 { 18 j++; k++; 19 if (s[j] != s[k]) neXt[j] = k; 20 else neXt[j] = neXt[k]; 21 } 22 else 23 { 24 k = neXt[k]; 25 } 26 } 27 } 28 29 int kmp(string s, string p) 30 { 31 int i = 0, j = 0; 32 int m = s.length(), n = p.length(); 33 while (i < m && j < n) 34 { 35 if (j == -1 || s[i] == p[j]) i++, j++; 36 else j = neXt[j]; 37 } 38 if (j == n) return i - j; 39 return -1; 40 } 41 42 bool solve(string x, string y, vector<pair<int, int>> & ans) 43 { 44 string z(x); 45 reverse(z.begin(), z.end()); 46 int m = x.length(); 47 int n = y.length(); 48 int start = 0; 49 while (start < n) 50 { 51 int l = 1, r = n - start, res = 0, pos = -1; 52 bool flg = true; 53 while (l <= r) 54 { 55 int mid = (l + r) >> 1; 56 string tmp = y.substr(start, mid); 57 getNext(tmp); 58 int p = kmp(x, tmp); 59 if (p != -1) 60 { 61 res = mid; pos = p; flg = true; l = mid + 1; 62 } 63 else if ((p = kmp(z, tmp)) != -1) 64 { 65 res = mid; pos = p; flg = false; l = mid + 1; 66 } 67 else r = mid - 1; 68 } 69 if (!res) return false; 70 if (flg) ans.push_back(pair<int, int>(pos + 1, pos + res)); 71 else ans.push_back(pair<int, int>(m - pos, m - pos - res + 1)); 72 start += res; 73 } 74 return true; 75 } 76 77 int main() 78 { 79 string x, y; 80 cin >> x >> y; 81 vector<pair<int, int>> res; 82 if (solve(x, y, res)) 83 { 84 cout << res.size() << endl; 85 for (int i = 0; i < res.size(); i++) 86 cout << res[i].first << " " << res[i].second << endl; 87 } 88 else 89 { 90 puts("-1"); 91 } 92 return 0; 93 }