# frozen_string_literal: true in_n, in_m = gets.chomp.split.map(&:to_i) in_s = in_n.times.map { gets.chomp.chars } def gcp(me, opponent) if me == opponent 0 elsif [me, opponent] in ["G", "C"] | ["C", "P"] | ["P", "G"] 1 else -1 end end transposed = in_s.transpose won = Array.new(in_n, false) remaining = in_n result = [] HANDS = %w[G C P] transposed[..-2].each do |oppos| allowed = [0, 0, 0] won.zip(oppos) do |done, oppo| next if done HANDS.each_with_index do |g, i| case gcp(g, oppo) when 1 allowed[i] += 1 when -1 allowed[i] = -in_n end end end if allowed.all?(&:negative?) puts -1 exit end result << HANDS[allowed.index(&:positive?) || allowed.index(0)] won .zip(oppos) .each_with_index do |(done, oppo), i| next if done won[i] = true if gcp(result[-1], oppo) == 1 end end [transposed[-1]].each do |oppos| allowed = [true, true, true] won.zip(oppos) do |done, oppo| next if done HANDS.each_with_index { |g, i| allowed[i] = false if gcp(g, oppo) != 1 } end if allowed.all?(false) puts -1 exit end result << HANDS[allowed.index(true)] end puts result.join