Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- using namespace std;
- int main() {
- //input
- string s;
- cin >> s;
- int cost[26];
- for (int i=0; i<26; i++) {
- cin >> cost[i];
- }
- //checking if all chars in the string are ????...
- bool allAreQuesMark =0;
- for (int i=0; i<s.length(); i++) {
- if(s[i]=='?') allAreQuesMark=1;
- else { allAreQuesMark=0; break; }
- }
- //if so, print 0 as the total cost and aaaa... as the new string
- //and EXIT the code
- if(allAreQuesMark) {
- cout << 0 << endl;
- int n=s.length();
- while (n--) cout << 'a';
- return 0;
- }
- //if not...
- //check for each '?' in the string
- for (int i=0; i<s.length(); i++) {
- if (s[i] == '?') {
- int minCost=INT_MAX;
- int nextAlphaIdx= i+1;
- //if the next char after the '?' is also a '?' pass and check for the next
- for(int k=i+1; k<s.length(); k++) {
- if(isalpha(s[k])) {
- nextAlphaIdx = k; //seeing how many '?' we skipped
- break;
- }
- }
- for (int j=0; j<26; j++) {
- long long x;
- char replaceWith;
- //detecting what is the best cost alpha to replace the '?'
- if (i==0) x=abs(cost[j]-cost[s[nextAlphaIdx]-'a']); //if the '?' is the first char
- else if (i==s.length()-1) x=abs(cost[s[i-1]-'a']-cost[j]); //if the '?' is the last char
- else x = abs(cost[s[i-1]-'a']-cost[j]) + abs(cost[j]-cost[s[nextAlphaIdx]-'a']);
- if ( x < minCost ) {
- minCost = x; //getting the minimum cost
- replaceWith = char(j+'a');
- }
- //then replacing all the consecutive '?' at once with the alpha that got the min cost
- for (int k=i; k<nextAlphaIdx; k++)
- s[i] = replaceWith;
- }
- }
- }
- //now we've got the new smallest string with the least cost
- //calculating the total cost
- long long totalCost=0;
- for (int i=0; i<s.length()-1; i++) {
- totalCost += abs(cost[s[i]-'a']-cost[s[i+1]-'a']);
- }
- //printing the wanted output
- cout << totalCost << endl;
- cout << s;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment