lina_os

Untitled

Nov 27th, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. //input
  9. string s;
  10. cin >> s;
  11. int cost[26];
  12. for (int i=0; i<26; i++) {
  13. cin >> cost[i];
  14. }
  15. //checking if all chars in the string are ????...
  16. bool allAreQuesMark =0;
  17. for (int i=0; i<s.length(); i++) {
  18. if(s[i]=='?') allAreQuesMark=1;
  19. else { allAreQuesMark=0; break; }
  20. }
  21. //if so, print 0 as the total cost and aaaa... as the new string
  22. //and EXIT the code
  23. if(allAreQuesMark) {
  24. cout << 0 << endl;
  25. int n=s.length();
  26. while (n--) cout << 'a';
  27. return 0;
  28. }
  29. //if not...
  30. //check for each '?' in the string
  31. for (int i=0; i<s.length(); i++) {
  32. if (s[i] == '?') {
  33. int minCost=INT_MAX;
  34. int nextAlphaIdx= i+1;
  35. //if the next char after the '?' is also a '?' pass and check for the next
  36. for(int k=i+1; k<s.length(); k++) {
  37. if(isalpha(s[k])) {
  38. nextAlphaIdx = k; //seeing how many '?' we skipped
  39. break;
  40. }
  41. }
  42. for (int j=0; j<26; j++) {
  43. long long x;
  44. char replaceWith;
  45. //detecting what is the best cost alpha to replace the '?'
  46. if (i==0) x=abs(cost[j]-cost[s[nextAlphaIdx]-'a']); //if the '?' is the first char
  47. else if (i==s.length()-1) x=abs(cost[s[i-1]-'a']-cost[j]); //if the '?' is the last char
  48. else x = abs(cost[s[i-1]-'a']-cost[j]) + abs(cost[j]-cost[s[nextAlphaIdx]-'a']);
  49. if ( x < minCost ) {
  50. minCost = x; //getting the minimum cost
  51. replaceWith = char(j+'a');
  52. }
  53. //then replacing all the consecutive '?' at once with the alpha that got the min cost
  54. for (int k=i; k<nextAlphaIdx; k++)
  55. s[i] = replaceWith;
  56. }
  57. }
  58. }
  59. //now we've got the new smallest string with the least cost
  60. //calculating the total cost
  61. long long totalCost=0;
  62. for (int i=0; i<s.length()-1; i++) {
  63. totalCost += abs(cost[s[i]-'a']-cost[s[i+1]-'a']);
  64. }
  65. //printing the wanted output
  66. cout << totalCost << endl;
  67. cout << s;
  68. return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment