UVA 12467 - Secret Word

UVA 12467 - Secret Word

kmp+二分,二分枚举答案的长度,用kmp判断是否合法

#include  using namespace std; #define rint register int #define rll register long long #define long long ll const int maxn = 1e6 + 100; char a[maxn], b[maxn]; int pi[maxn], f[maxn]; bool check(int mid, int n) { pi[mid] = 0; for (rint i = mid + 1, j = 0; i <= n; i++) { while (j > 0 && a[i] != a[mid + j]) j = pi[j + mid - 1]; if (a[i] == a[mid + j]) j++; pi[i] = j; } for (int i = 1, j = 0; i <= n; i++) { while (j > 0 && (j == n || b[i] != a[j + mid])) j = pi[j + mid - 1]; if (b[i] == a[j + mid]) j++; f[i] = j; if (f[i] == n - mid + 1) return true; } return false; } int main() { // freopen("in.txt", "r", stdin); rint _; scanf("%d", &_); while (_--) { scanf("%s", b + 1); rint n = strlen(b + 1); rint tot = 0; for (int i = n; i >= 1; i--) { a[++tot] = b[i]; } a[n + 1] = '\0'; rint l = 1, r = n, mid; while (l < r) { mid = (l + r) >> 1; if (check(mid, n)) r = mid; else l = mid + 1; } for (rint i = l; i <= n; i++) { printf("%c", a[i]); } printf("\n"); } return 0; }

你可能感兴趣的:(UVA 12467 - Secret Word)