#include<bits/stdc++.h>
using namespace std;
stack<int> s[1010];
int main()
{
	int n, m;
	scanf("%d%d",&n,&m);
	while(m--)
	{
		int x;
		scanf("%d",&x);
		if(x == 0)
		{
			int y, z;
			scanf("%d%d",&y,&z);
			s[y].push(z);
		}
		else if(x == 1)
		{
			int y;
			scanf("%d",&y);
			if(s[y].size())printf("%d\n",s[y].top());
			//else printf("\n");
		}
		else if(x == 2)
		{
			int y;
			scanf("%d",&y);
			if(s[y].size())s[y].pop();
		}
	}
	return 0;
}
