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

#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define ALL(v) (v).begin(), (v).end()
#define p(s) cout<<(s)<<endl
#define p2(s, t) cout << (s) << " " << (t) << endl
#define br() p("")
#define pn(s) cout << (#s) << " " << (s) << endl

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    // input
    ll N, Q;
    cin >> N >> Q;

    stack<ll> sta[N];

    FOR(q, 0, Q){
        ll a;
        cin >> a;

        // push
        if(a==0){
            ll t, x;
            cin >> t >> x;
            sta[t].push(x);
        }
        // top
        else if(a==1){
            ll t;
            cin >> t;
            if(sta[t].size()>0){
                p(sta[t].top());
            }
        }
        // pop
        else{
            ll t;
            cin >> t;
            if(sta[t].size()>0){
                sta[t].pop();
            }
        }
    }
    
    return 0;
}
