Advertisement
JohnJ2

z1002 two arrays

Nov 11th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.73 KB | None | 0 0
  1. # Time limit exceeded, test 4, time 2.043, memory   780 КБ
  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.   wcodes = []
  13.   gets.to_i.times {
  14.     word = gets.chomp
  15.     code = '';
  16.     word.each_char { |letter| code += codes[letter]}
  17.     next if words.include? word
  18.     words.push(word)
  19.     wcodes.push(code)
  20.   }
  21.  
  22.   xcodes = wcodes.sort()
  23.  
  24.   max_word_length = words.max_by {|k| k.length}.length
  25.   min_world_length = words.min_by {|k| k.length}.length
  26.   finds = [['']]
  27.   phone.each_char.with_index { |number, index|
  28.     to_delete = []
  29.     to_add = []
  30.     finds.each { |find|
  31.       find[-1] += number
  32.       if find.last.length > max_word_length
  33.         to_delete.push(find)
  34.         next
  35.       end
  36.       isset = find.last.length >= min_world_length && xcodes.include?(find.last)
  37.       if index < phone.length - 1
  38.         if isset
  39.             branch = []
  40.             find.each {|part| branch.push(part.clone)}
  41.             to_add.push(branch)
  42.             find.push('')
  43.         end
  44.       elsif !isset
  45.         to_delete.push(find)
  46.       end
  47.     }
  48.     to_delete.each { |find| finds.delete(find) }
  49.     to_add.each { |find| finds.push(find) }
  50.   }
  51.  
  52.   if (finds.empty?)
  53.     puts 'No solution.'
  54.   else
  55.     shortest = finds.min_by { |find| find.length }
  56.     answer = []
  57.     shortest.each { |code| answer.push(words[wcodes.index(code)])}
  58.     puts answer * ' '
  59.   end
  60. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement