
fun main(args:Array<String>):Unit {
    val (n, q) = readLine()!!.split(' ').map(String::toInt)
    val stacks = Array(n){Stack<Int>()}
    repeat(q){
        val query = readLine()!!.split(' ').map(String::toInt)
        when(query.first()){
            0 -> stacks[query[1]].push(query.last())
            1 -> if (stacks[query.last()].isNotEmpty) println(stacks[query.last()].top())
            else -> if (stacks[query.last()].isNotEmpty) stacks[query.last()].pop()
        }
    }
}

sealed class ImmutableList<out T>{
    object Nil:ImmutableList<Nothing>()
    data class Cons<out T>(val head:T, val tail:ImmutableList<T>):ImmutableList<T>()
}
class Stack<T>{
    private var mStack:ImmutableList<T> = ImmutableList.Nil
    fun push(value:T):Unit {
        mStack = ImmutableList.Cons(value, mStack)
    }
    fun top():T = (mStack as ImmutableList.Cons).head
    fun pop():Unit {
        mStack = (mStack as ImmutableList.Cons).tail
    }
    val isEmpty:Boolean
        get() = mStack == ImmutableList.Nil
    val isNotEmpty:Boolean
        get() = !isEmpty
}
