#include <bits/stdc++.h>
#include <vector>
 
typedef long long ll;
#define SIZE_OF_ARRAY(array) (sizeof(array)/sizeof(array[0]))
#define rep(i, n) for (int i = 0; i < (n); ++i)
const double PI=3.14159265358979323846;
 
using namespace std;
 
int main() {

	int n, q;
	cin >> n >> q;

	stack<int> s[n];

	int a, b, c;

	rep(i, q) {
		cin >> a >> b;

		switch(a) {

			case 0:
				cin >> c;
				s[b].push(c);
				break;

			case 1:
				if (!s[b].empty())
					cout << s[b].top() << endl;
				break;
			
			case 2:
				if (!s[b].empty())
					s[b].pop();
				break;
		}
	}


}
