fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. string s;
  7. int n;
  8. vector<string> v;
  9. vector<int> dp;
  10.  
  11. bool makable(string a, string b) {
  12. sort(a.begin(), a.end());
  13. sort(b.begin(), b.end());
  14. return a == b;
  15. }
  16.  
  17. int check(string a, string b) {
  18. if(!makable(a, b))
  19. return 1e9;
  20.  
  21. int cnt = 0;
  22. for(int i = 0; i < a.size(); i++)
  23. if(a[i] != b[i])
  24. cnt++;
  25.  
  26. return cnt;
  27. }
  28.  
  29. int main() {
  30. cin >> s >> n;
  31. v.resize(n);
  32. for(auto& a : v)
  33. cin >> a;
  34. dp.resize(s.size()+1, 1e9);
  35. dp[0] = 0;
  36.  
  37. for(int i = 0; i <= s.size(); i++) {
  38. for(auto& w : v) {
  39. if(i < w.size())
  40. continue;
  41.  
  42. string ch = s.substr(i-w.size(), w.size());
  43.  
  44. int c = check(w, ch);
  45. dp[i] = min(dp[i], dp[i+1-w.size()]+c);
  46. cout << i-w.size() << "\n";
  47. cout << ch << ":" << c << "\n";
  48. }
  49. }
  50.  
  51. if(dp[s.size()] > s.size())
  52. cout << -1;
  53. else
  54. cout << dp[s.size()];
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5460KB
stdin
neotowheret
4
one
two
three
there
stdout
0
neo:3
0
neo:1000000000
1
eot:1000000000
1
eot:1000000000
2
oto:1000000000
2
oto:1000000000
0
neoto:1000000000
0
neoto:1000000000
3
tow:1000000000
3
tow:2
1
eotow:1000000000
1
eotow:1000000000
4
owh:1000000000
4
owh:1000000000
2
otowh:1000000000
2
otowh:1000000000
5
whe:1000000000
5
whe:1000000000
3
towhe:1000000000
3
towhe:1000000000
6
her:1000000000
6
her:1000000000
4
owher:1000000000
4
owher:1000000000
7
ere:1000000000
7
ere:1000000000
5
where:1000000000
5
where:1000000000
8
ret:1000000000
8
ret:1000000000
6
heret:3
6
heret:5
-1