Advertisement
Fastrail08

Maximum Score of Words

Apr 23rd, 2025
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void getMaxScore(vector<string> &words, vector<int> &frequencies, vector<int> &scores, int index, int currScore, int &maxScore){
  5.     if(index == words.size()){
  6.         maxScore = max(maxScore, currScore);
  7.         return;
  8.     }
  9.    
  10.     //current word excluded
  11.     getMaxScore(words, frequencies, scores, index + 1, currScore, maxScore);
  12.    
  13.     //deduct frequencies and add score if word included in set
  14.     bool charLeftToUse = true;
  15.     for(int i = 0; i < words[index].size(); i++){
  16.         char charInWord = words[index][i];
  17.         frequencies[charInWord - 'a']--;
  18.         if(frequencies[charInWord - 'a'] < 0){
  19.             charLeftToUse = false;
  20.         }
  21.         currScore += scores[charInWord - 'a'];
  22.     }
  23.    
  24.      //current word included, but if there is enough frequencies of the character present in word
  25.     if(charLeftToUse){
  26.         getMaxScore(words, frequencies, scores, index + 1, currScore, maxScore);
  27.     }
  28.    
  29.     //revert the state of frequencies and currScore before returning
  30.     for(int i = 0; i < words[index].size(); i++){
  31.         char charInWord = words[index][i];
  32.         frequencies[charInWord - 'a']++;
  33.         currScore -= scores[charInWord - 'a'];
  34.     }
  35.    
  36. }
  37.  
  38. int main() {
  39.     // your code goes here
  40.    
  41.     int w, f, maxScore = 0;
  42.     cin >> w;
  43.     vector<string> words(w);
  44.     vector<int> frequencies(26, 0);
  45.     vector<int> scores(26, 0);
  46.     for(int i = 0; i < w; i++){
  47.         cin >> words[i];
  48.     }
  49.    
  50.    
  51.     cin >> f;
  52.     char c;
  53.     for(int i = 0; i < f; i++){
  54.         cin >> c;
  55.         frequencies[c - 'a']++;
  56.     }
  57.    
  58.     // for(int i = 0; i < frequencies.size(); i++){
  59.     //     cout << char (i + 'a') << ": " << frequencies[i] << '\n';
  60.     // }
  61.    
  62.     for(int i = 0; i < scores.size(); i++){
  63.         cin >> scores[i];
  64.     }
  65.    
  66.     // for(int i = 0; i < scores.size(); i++){
  67.     //     cout << char (i + 'a') << ": " << scores[i] << '\n';
  68.     // }
  69.     getMaxScore(words, frequencies, scores, 0, 0, maxScore);
  70.     cout << maxScore << '\n';
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement