ABC335C - Loong Tracking

problem link

A brute force solution to this problem would be modifying all n n n body parts with each move. However, one might notice that we don’t have to maintain the entire snake body dynamically. Since each part will take the place of the previous part, the i i ith part will always be i − 1 i-1 i1 indices down from the snake head.

With this conclusion, we can simply update the snake head position in a stack-like data structure. In each new move, we append the new position of the snake head to the stack. During queries, the i i ith body part would be the i i ith element down the stack. This gives us O ( n + q ) \mathcal O(n+q) O(n+q) complexity.

#include
#include
#include
#include
#include
using namespace std;
const int Maxn=2e6+10;
int a[Maxn],b[Maxn];
int n,q,cnt;
inline int read()
{
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0' || ch>'9'){if(ch=='-')w-=1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
int main()
{
	// freopen("in.txt","r",stdin);
	n=read(),q=read(),cnt=n;
	for(int i=1;i<=n;++i)
	a[i]=n-i+1;
	while(q--)
	{
		int opt=read();
		if(opt==1)
		{
			// printf("mod\n");
			string s;
			cin>>s;
			int x=a[cnt],y=b[cnt];
			if(s[0]=='U')++y;
			if(s[0]=='D')--y;
			if(s[0]=='L')--x;
			if(s[0]=='R')++x;
			a[++cnt]=x;
			b[cnt]=y;
		}
		else
		{
			int p=read();
			printf("%d %d\n",a[cnt-p+1],b[cnt-p+1]);
		}
	}
	return 0;
}

你可能感兴趣的:(AtCoder,题解,算法)