fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. ios::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7.  
  8. long long c1, c2;
  9. string s;
  10. cin >> c1 >> c2 >> s;
  11.  
  12. int n = s.size();
  13.  
  14. // Problem: Split string into pieces to minimize cost
  15. // Cost = (adjacent equal pairs) * c1 + (number of splits) * c2
  16.  
  17. // pre[i] = number of adjacent equal pairs in s[0..i-1]
  18. // Prefix sum of pairs (s[0],s[1]), (s[1],s[2]), ..., (s[i-2],s[i-1])
  19. vector<int> pre(n + 1, 0);
  20. for (int i = 1; i < n; i++) {
  21. pre[i + 1] = pre[i];
  22. if (s[i - 1] == s[i]) {
  23. pre[i + 1]++;
  24. }
  25. }
  26.  
  27. // dp[i] = min cost to optimally split s[0..i-1]
  28. const long long INF = 1e18;
  29. vector<long long> dp(n + 1, INF);
  30. dp[0] = 0; // empty string has cost 0
  31.  
  32. // For each position i, try all possible ways to form the last piece
  33. for (int i = 1; i <= n; i++) {
  34. // Try making last piece from s[j..i-1]
  35. for (int j = 0; j < i; j++) {
  36. // Count adjacent equal pairs in substring s[j..i-1]
  37. // Pairs are: (s[j],s[j+1]), (s[j+1],s[j+2]), ..., (s[i-2],s[i-1])
  38. // These correspond to indices j+1, j+2, ..., i-1 in the prefix array
  39. int cnt = pre[i] - pre[j + 1];
  40.  
  41. // Cost of pairs in this piece
  42. long long cost = (long long)cnt * c1;
  43.  
  44. // Add split cost (c2) if this isn't the first piece
  45. if (j > 0) cost += c2;
  46.  
  47. // Update minimum cost to reach position i
  48. dp[i] = min(dp[i], dp[j] + cost);
  49. }
  50. }
  51.  
  52. cout << dp[n] << "\n";
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
0