HDU/HDOJ 1867 A + B for you again
仔细了解KMP之后再看这题就会发现是裸题。
因为kmp我们可以求出s的f数组,表示能与p的多少前缀匹配。那么我们只需取f[s.size() - 1]即可。
1 #include <cstdio> 2 #include <string> 3 #include <iostream> 4 using std::string; 5 using std::cin; 6 using std::cout; 7 using std::endl; 8 9 int nex[100010]; 10 11 string KMPsolve(string s, string p) { 12 nex[0] = 0; 13 for(int i = 1, j = 0; i < p.size(); i++) { 14 while(j && p[i] != p[j]) { 15 j = nex[j - 1]; 16 } 17 if(p[i] == p[j]) j++; 18 nex[i] = j; 19 } 20 int j = 0; 21 for(int i = 0; i < s.size(); i++) { 22 while(j && s[i] != p[j]) { 23 j = nex[j - 1]; 24 } 25 if(s[i] == p[j]) j++; 26 if(j == p.size() && (i + 1) != s.size()) { 27 j = nex[j - 1]; 28 } 29 } 30 for(; j < p.size(); j++) { 31 s += p[j]; 32 } 33 return s; 34 } 35 36 int main() { 37 string s, p; 38 while(std::cin >> s >> p) { 39 string a = KMPsolve(s, p); 40 string b = KMPsolve(p, s); 41 if(a.size() < b.size()) { 42 cout << a << endl; 43 } 44 else if(a.size() > b.size()) { 45 cout << b << endl; 46 } 47 else { 48 cout << (a < b ? a : b) << endl; 49 } 50 } 51 return 0; 52 }