#include<iostream>
#include<stack>
using namespace std;
const int N=1010;
int main()
{
    int T,Z;
    stack<int> s[N];
    cin>>Z>>T;
    while(T--)
    {
        int c;
        cin>>c;
        switch (c)
        {
            case 0:
        {
            int n,m;
            cin>>n>>m;
            s[n].push(m);
        }break;
        case 1:
        {
            int n;
            cin>>n;
            if(s[n].size())
            cout<<s[n].top()<<endl;
        }break;
        case 2:
        {
            int n;
            cin>>n;
            if(s[n].size())
            {
                s[n].pop();
            }
        }break;
        default: break;
        }
        
    }
}
