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

int main() {
    int n, q;
    cin >> n >> q;
    vector<stack<int>> s(n);
    int a, t, x;
    while (q--) {
        cin >> a >> t;
        if (a == 0) {
            cin >> x;
            s[t].push(x);
        }
        else if (a == 1) {
            if (s[t].empty())
                continue;
            else
                cout << s[t].top() << endl;
        }
        else {
            if (s[t].empty())
                continue;
            else
                s[t].pop();
        }
    }
}
