
def deadlock?(commands)
  if commands.any? {|c| samelock? c }
    true
  elsif rotatelock? commands
    true
  elsif commands.combination(2).to_a.any? {|a, b| swaplock? a, b }
    true
  else
    false
  end
end

def rotatelock?(commands)
  commands.any? do |command|
    endlock = command[0]
    looks = [command]
    while looks.size > 0
      look_command = looks.pop

      return true if  endlock == look_command[-1]

      looks.concat commands.select {|c| c[0] == look_command[-1] }
    end
    false
  end
end

def swaplock?(command1, command2)
  combi = command1.split("").combination(2).to_a
  if combi.any? {|arr| swaplock_match? arr, command1, command2 }
    true
  else
    false
  end
end

def swaplock_match?(char_combi, command1, command2)
  if /(.*)#{char_combi[1]}(.*)#{char_combi[0]}/ =~ command2
    search_s = $1 + $2
    if search_s.split("").any? {|c| command1[0..search_s.length+1].include? c }
      false
    else
      true
    end
  else
    false
  end
end

def samelock?(command)
  command.size != command.split("").uniq.size
end

while true
  n = gets.chomp.to_i

  break if n == 0

  commands = gets.chomp.split("u")

  if deadlock? commands
    puts "UNSAFE"
  else
    puts "SAFE"
  end
end