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

int main()
{
    int n, q, t, a, x;
    cin >> n >> q;

    stack<int> s[n];

    while (q--)
    {
        cin >> t;
        if (t == 0)
        {
            cin >> a >> x;
            s[a].push(x);
        }
        if (t == 1)
        {
            cin >> a;
            if (s[a].size() != 0)
                cout << s[a].top() << endl;
        }
        if (t == 2)
        {
            cin >> a;
            if (s[a].size() != 0)
                s[a].pop();
        }
    }
}

