Baltic OI 2019 - Necklace
Author: Andi Qu
Appears In
Solution 1 (Magic DP)
Time complexity: . Memory complexity: .
This section is not complete.
The editorial describes this approach so awfully :(. "Analyze the recurrences carefully"
Code
//DP: time O(n^2), mem O(n)#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;int solve_noflip(string &s, string &t, int *loc) {int n = s.size(); // vertical
Solution 2 (KMP)
Time complexity: . Memory complexity: .
Let the two strings be and , and their lengths be and respectively.
For simplicity, assume that we can't flip the necklace over. (To handle the case where we can, just reverse , run our algorithm again, and take the best result.)
We essentially want to find two strings and , and two indices and such that:
- is a suffix of and a prefix of .
- is a prefix of and a suffix of .
- is maximal.
We can thus test each to find the best for that , and then take the best overall result.
To find the best , we first reverse and split at index . This turns the subproblem into finding the longest common prefix/suffix between two pairs of strings. This is a classical application of KMP, so we can solve this subproblem in time and memory.
Code
#include <bits/stdc++.h>typedef long long ll;using namespace std;int p1[6002], p2[6002];void fill_p(string s, int *p) {for (int i = 1; i < s.size(); i++) {int j = p[i - 1];while (j && s[i] != s[j]) j = p[j - 1];
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!