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. // Example: "aabbc" -> pre = [0, 0, 1, 1, 2, 2]
  19. vector<int> pre(n + 1, 0);
  20. for (int i = 0; i < n - 1; i++) {
  21. pre[i + 1] = pre[i];
  22. if (s[i] == s[i + 1]) {
  23. pre[i + 1]++;
  24. }
  25. }
  26. pre[n] = pre[n - 1];
  27.  
  28. // dp[i] = min cost to optimally split s[0..i-1]
  29. const long long INF = 1e18;
  30. vector<long long> dp(n + 1, INF);
  31. dp[0] = 0; // empty string has cost 0
  32.  
  33. // For each position i, try all possible ways to form the last piece
  34. for (int i = 1; i <= n; i++) {
  35. // Try making last piece from s[j..i-1]
  36. for (int j = 0; j < i; j++) {
  37. // Count adjacent equal pairs in range [j, i)
  38. int cnt = pre[i] - pre[j];
  39.  
  40. // Cost of pairs in this piece
  41. long long cost = (long long)cnt * c1;
  42.  
  43. // Add split cost (c2) if this isn't the first piece
  44. if (j > 0) cost += c2;
  45.  
  46. // Update minimum cost to reach position i
  47. dp[i] = min(dp[i], dp[j] + cost);
  48. }
  49. }
  50.  
  51. cout << dp[n] << "\n";
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
0