#include <bits/stdc++.h>
using namespace std;

void solve(stack<int> box[]){
    int x; cin >> x;
    switch(x){
        case 0:
            int t0, y; cin >> t0 >> y;
            box[t0].push(y);
            break;
        case 1:
            int t1; cin >> t1;
            if(!box[t1].empty()) cout << box[t1].top() << endl;
            break;
        case 2:
            int t2; cin >> t2;
            if(!box[t2].empty()) box[t2].pop();
            break;
        default: cout << "ERROR" << endl;
    }
}

int main(){
    int n, q; cin >> n >> q;
    stack<int> box[n];
    while(q--){
        solve(box);
    }
    return 0;
}
