Advertisement
JohnJ2

z1002 hash

Nov 11th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.52 KB | None | 0 0
  1. #   Memory limit exceeded, test 5, time 1.575, memory   82 888 КБ
  2. codes = {
  3.     'a' => '2', 'b' => '2', 'c' => '2', 'd' => '3', 'e' => '3', 'f' => '3', 'g' => '4', 'h' => '4', 'i' => '1',
  4.     'j' => '1', 'k' => '5', 'l' => '5', 'm' => '6', 'n' => '6', 'o' => '0', 'p' => '7', 'q' => '0', 'r' => '7',
  5.     's' => '7', 't' => '8', 'u' => '8', 'v' => '8', 'w' => '9', 'x' => '9', 'y' => '9', 'z' => '0',
  6. }
  7.  
  8. while true
  9.   phone = gets.chomp
  10.   break if phone == '-1'
  11.   words = {}
  12.   gets.to_i.times {
  13.     word = gets.chomp
  14.     code = '';
  15.     word.each_char { |letter| code += codes[letter]}
  16.     words[code] = word
  17.   }
  18.  
  19.   max_word_length = words.keys.max_by {|k| k.length}.length
  20.   finds = [['']]
  21.   phone.each_char.with_index { |number, index|
  22.     to_delete = []
  23.     to_add = []
  24.     finds.each { |find|
  25.       find[-1] += number
  26.       if find.last.length > max_word_length
  27.         to_delete.push(find)
  28.         next
  29.       end
  30.       if index < phone.length - 1
  31.         if words.key?(find.last)
  32.           branch = []
  33.           find.each {|part| branch.push(part.clone)}
  34.           to_add.push(branch)
  35.           find.push('')
  36.         end
  37.       elsif !words.key?(find.last)
  38.         to_delete.push(find)
  39.       end
  40.     }
  41.     to_delete.each { |find| finds.delete(find) }
  42.     to_add.each { |find| finds.push(find) }
  43.   }
  44.  
  45.   if (finds.empty?)
  46.     puts 'No solution.'
  47.   else
  48.     shortest = finds.min_by { |find| find.length }
  49.     answer = []
  50.     shortest.each { |code| answer.push(words[code])}
  51.     puts answer * ' '
  52.   end
  53. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement