n, q = gets.split.map(&:to_i)
a = n.times.map{[]}

q.times do
  command, num1, num2 = gets.split.map(&:to_i)
  case command
  when 0
    a[num1].push num2
  when 1
    puts a[num1][-1] if !a[num1].empty?
  else
    a[num1].pop if !a[num1].empty?
  end
end
