标签:扩展kmp
asdf sdfg asdf ghjk
asdfg asdfghjk
Statistic | Submit | Discuss | Note
这题我是用扩展kmp做的, 做两次就行
/************************************************************************* > File Name: hdu1867.cpp > Author: ALex > Mail: zchao1995@gmail.com > Created Time: 2015年02月02日 星期一 17时03分34秒 ************************************************************************/ #include <map> #include <set> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const double pi = acos(-1); const int inf = 0x3f3f3f3f; const double eps = 1e-15; typedef long long LL; typedef pair <int, int> PLL; const int N = 200110; char S[N], T[N]; int next[N]; int extend[N]; char A1[N], A2[N]; void EXTEND_KMP (char S[], char T[]) { int lens = strlen (S); int lent = strlen (T); next[0] = lent; int i, j, p, L; j = 0; while (j + 1 < lent && T[j] == T[j + 1]) // 先求出next[1] { ++j; } next[1] = j; int a = 1; for (i = 2; i < lent; ++i) { p = next[a] + a - 1; L = next[i - a]; if (i + L < p + 1) { next[i] = L; } else { j = max (0, p - i + 1); while (i + j < lent && T[i + j] == T[j]) { ++j; } next[i] = j; a = i; } } j = 0; while (j < lens && S[j] == T[j]) { ++j; } extend[0] = j; a = 0; for (i = 1; i < lens; ++i) { p = extend[a] + a - 1; L = next[i - a]; if (L + i < p + 1) { extend[i] = L; } else { j = max(0, p - i + 1); while (i + j < lens && j < lent && S[i + j] == T[j]) { ++j; } extend[i] = j; a = i; } } } int main () { while (~scanf("%s%s", S, T)) { EXTEND_KMP (S, T); int lens = strlen (S); int lent = strlen (T); int s = -1; strcpy (A1, S); for (int i = 0; i < lens; ++i) { if (extend[i] + i == lens) { s = i; break; } } if (s == -1) { strcat (A1, T); } else { int cnt = lens; for (int i = lens - s; i < lent; ++i) { A1[cnt++] = T[i]; } A1[cnt] = '\0'; } memset (next, 0, sizeof(next)); memset (extend, 0, sizeof(extend)); strcpy (A2, T); EXTEND_KMP (T, S); s = -1; for (int i = 0; i < lent; ++i) { if (extend[i] + i == lent) { s = i; break; } } if (s == -1) { strcat (A2, S); } else { int cnt = lent; for (int i = lent - s; i < lens; ++i) { A2[cnt++] = S[i]; } A2[cnt] = '\0'; } int len1 = strlen (A1); int len2 = strlen (A2); if (len1 < len2) { printf("%s\n", A1); } else if (len1 > len2) { printf("%s\n", A2); } else { if (strcmp (A1, A2) < 0) { printf("%s\n", A1); } else { printf("%s\n", A2); } } } return 0; }
标签:扩展kmp
原文地址:http://blog.csdn.net/guard_mine/article/details/43411631