#include <iostream>
#include <vector>
//#define
using namespace std;

int main()
{
    int n, q;
    cin >> n >> q;
    int *length = new int[n]{0};        // all 0?
    vector<vector<int> > arr(n);

    int flag, index, num;
    for (int i = 0; i < q; i++)
    {
        cin >> flag;
        switch(flag)
        {
        case 0:
            cin >> index >> num;
            if (length[index] < arr[index].size())
            {
                arr[index][length[index]] = num;
            }
            else
            {
                arr[index].push_back(num);
            }
            length[index]++;
            break;
        case 1:
            cin >> index;
            if (length[index] > 0)
            {
                int t = length[index];
                cout << arr[index][--t] << "\n";
            }
            break;

        case 2:
            cin >> index;
            if (length[index] > 0)
            {
                length[index]--;
            }
            break;
        default:
            break;
        }
    }

    return 0;
}

