Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- char graph[120][120];
- char words[50010][60];
- char number[120] = "";
- int used[120];
- int n;
- int w;
- // a, b, c, d, e, f, g, h, i, j, k, l ,m, n, o, p, q, r, s, t, u, v, w, x, y, z
- int keys[26] = {2, 2, 2, 3, 3, 3, 4, 4, 1, 1, 5, 5, 6, 6, 0, 7, 0, 7, 7, 8, 8, 8, 9, 9, 9, 0};
- void addEdge (int from, int to, int id) {
- //std::cout << from << "->" << to << std::endl;
- graph[from][to] = id;
- }
- void toNumbers(char * pattern, int m) {
- for(int i = 0; i < m; i ++)
- pattern[i] = '0' + keys[pattern[i] - 'a'];
- }
- void KMP (char * pattern, int id) {
- int p[100];
- p[0] = -1;
- int m = std::strlen(pattern);
- //toNumbers(pattern, m);
- //PF
- for(int q = 1; q <= m; q ++) {
- p[q] = p[q - 1] + 1;
- while(p[q] > 0 && pattern[q - 1] != pattern[p[q] - 1])
- p[q] = p[p[q] - 1] + 1;
- }
- //Match
- for(int i = 0, q = 0; i < n; i ++) {
- while(q > 0 && ('0' + keys[pattern[q] - 'a']) != number[i])
- q = p[q];
- if(('0' + keys[pattern[q] - 'a']) == number[i])
- q ++;
- if(q == m) {
- addEdge(i - m + 1, i + 1, id);
- q = p[q];
- }
- }
- }
- struct qi {
- int num, depth, from, prev;
- qi(int num_, int depth_, int from_, int prev_) {
- num = num_; depth = depth_;
- from = from_; prev = prev_;
- }
- qi() {num = depth = 0; from = -1; prev = -1;}
- };
- void answer() {
- for(int i = 0; i < n; i ++)
- used[i] = 0;
- qi * queue = new qi[w], curr;
- int high = 1, low = 0;
- queue[0] = qi();
- used[0] = 1;
- while(low < high) {
- curr = queue[low++];
- if(curr.num == n) break;
- for(int i = 0; i <= n; i ++) {
- if(graph[curr.num][i] != -1 && !used[i]) {
- queue[high++] = qi(i,curr.depth + 1,curr.num, low - 1);
- used[i] = 1;
- }
- }
- }
- if(curr.num != n) {
- std::cout << "No solution.";
- } else {
- int _n = curr.depth, *ans;
- try{
- ans = new int[_n];}
- catch(...){
- std::cout << "WTF!?";
- }
- do {
- ans[curr.depth - 1] = graph[curr.from][curr.num];
- curr = queue[curr.prev];
- }while(curr.depth != 0);
- for(int i = 0; i < _n; i ++)
- std::cout << words[ans[i]] << " ";
- delete[] ans;
- }
- std::cout << std::endl;
- }
- void main() {
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "rt", stdin);
- freopen("output.txt", "wt", stdout);
- #endif
- std::ios_base::sync_with_stdio(false);
- while(std::cin >> number) {
- if(number[0] == '-')
- break;
- n = std::strlen(number);
- for(int i = 0; i <= n; i ++) {
- for(int j = 0; j <= n; j ++)
- graph[i][j] = -1;
- }
- std::cin >> w;
- for(int i = 0; i < w; i ++) {
- std::cin >> words[i];
- KMP(words[i], i);
- }
- answer();
- }
- }
Add Comment
Please, Sign In to add comment