#include <iostream>
#include <stack>
using namespace std;

int main()
{
    long long size;
    cin >> size;
    stack<long long> n[size];
    long long q;
    cin >> q;
    for (long long i = 0; i < q; i++)
    {
        long long a, t, x;
        cin >> a >> t;
        if (a == 0)
        {
            cin >> x;
            n[t].push(x);
        }
        else if (a == 1)
        {
            if(n[t].empty() == 1) continue;
            cout << n[t].top() << endl;
        }
        else
        {
            if(n[t].empty() == 1) continue;
            n[t].pop();
        }
    }

    return 0;
}
