Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- #include <map>
- #include <string>
- #include <vector>
- #include <algorithm>
- using std::fill;
- using std::string;
- using std::vector;
- const int MAXN = 50000 * 101;
- int nodes[MAXN][10];
- bool leaf[MAXN];
- void add_to_bor(std::string str, int& last) {
- int cur = 0;
- for (int i = str.size() - 1; i > -1; i--) {
- if (nodes[cur][str[i] - '0'] == 0) {
- nodes[cur][str[i] - '0'] = last;
- last++;
- }
- cur = nodes[cur][str[i] - '0'];
- }
- leaf[cur] = true;
- }
- void task() {
- std::ofstream fout("output.txt");
- std::ifstream fin("input.txt");
- string number = "";
- fin >> number;
- int count_words = 0;
- fin >> count_words;
- std::map <char, int> encoding_dict = { {'1', 1 }, {'2' , 2} , {'3' , 3}, {'4' , 4}, {'5' , 5}, {'6' , 6},
- {'7' , 7}, {'8' , 8}, {'9' , 9}, {'0' , 0}, {'Q' , 0}, {'W' , 9}, {'E' , 3}, {'R' , 7},{'T' , 8}, {'Y' , 9},
- {'U', 8}, {'I' , 1}, {'O' , 0}, {'P' , 7}, {'A' , 2}, {'S' , 7}, {'D' , 3}, {'F' , 3}, {'G' , 4}, {'H' , 4},
- {'J' , 1}, {'K' , 5}, {'L' , 5}, {'Z' , 0}, {'X' , 9}, {'C' , 2}, {'V' , 8}, {'B' , 2}, {'N' , 6}, {'M' , 6} };
- std::map <string, string> words;
- memset(nodes, 0, sizeof(nodes));
- memset(leaf, false, sizeof(leaf));
- int last = 1;
- for (int i = 0; i < count_words; i++) {
- string str_word = "";
- fin >> str_word;
- string str_number = "";
- for (int j = 0; j < str_word.size(); j++)
- str_number += encoding_dict[str_word[j]] + '0';
- add_to_bor(str_number, last);
- words[str_number] = str_word ;
- }
- int* dp = new int[number.size()];
- fill(dp, dp + number.size(), 0);
- int* index = new int[number.size()];
- fill(index, index + number.size(), -2);
- for (int i = 0; i < number.size(); i++) {
- int cur = 0;
- string str = "";
- for (int j = i; j > std::max(-1, i - 100); j--) {
- if (nodes[cur][number[j] - '0'] == 0)
- break;
- if (leaf[nodes[cur][number[j] - '0']])
- if (j != 0) {
- if (dp[j - 1] != 0 && dp[i] != 0) {
- dp[i] = std::min(dp[j - 1] + 1, dp[i]);
- if (dp[i] == dp[j - 1] + 1)
- index[i] = j - 1;
- }
- else if (dp[j - 1] != 0) {
- dp[i] = dp[j - 1] + 1;
- index[i] = j - 1;
- }
- }
- else {
- dp[i] = 1;
- index[i] = -1;
- }
- cur = nodes[cur][number[j] - '0'];
- }
- }
- if (dp[number.size() - 1] == 0)
- fout << "No solution" << std::endl;
- else {
- int i = number.size() - 1;
- vector <string> list_of_number;
- while (i > -1){
- list_of_number.push_back(words[number.substr(index[i] + 1, i - index[i])]);
- i = index[i];
- }
- fout << dp[number.size() - 1] << std::endl;
- for (int i = list_of_number.size() - 1; i > -1; i--)
- fout << list_of_number[i] + ' ';
- }
- fout.close();
- fin.close();
- }
- int main() {
- task();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement