#include <iostream> #include <vector> #include <string> #include <unorderedmap> using…
- User
#include #include #include #include <unordered_map>
using namespace std;
unordered_map<char, int> countLetters(const string& str) { unordered_map<char, int> letterCount; for (char c : str) { letterCount[c]++; } return letterCount; }
bool canFormString(const vector& words, const string& target) { unordered_map<char, int> targetCount = countLetters(target); unordered_map<char, int> combinedCount;
for (const string& word : words) { unordered_map<char, int> wordCount = countLetters(word); for (const auto& pair : wordCount) { combinedCount[pair.first] += pair.second; } } return combinedCount == targetCount;}
void findWords(const vector& wordList, const string& target, vector& current, vector<vector>& results, int start, int maxWords) { if (current.size() > maxWords) return; if (canFormString(current, target)) { results.push_back(current); }
for (int i = start; i < wordList.size(); i++) { current.push_back(wordList[i]); findWords(wordList, target, current, results, i + 1, maxWords); current.pop_back(); }}
int main() { string targetString; int n;
cin >> targetString; cin >> n; vector<string> words(n); for (int i = 0; i < n; i++) { cin >> words[i]; } vector<vector<string>> results; vector<string> current; findWords(words, targetString, current, results, 0, 8); cout << std::endl << endl; // Вывод результата for (const auto& result : results) { for (const string& word : result) { cout << word << endl; } } return 0;}
Оптимизируй алгоритм
- Assistant