ABC335C - Loong Tracking

文章描述了一种在蛇游戏中利用栈数据结构简化蛇头位置更新和查询的方法,避免了维护整个蛇身的复杂性,提高了查询和更新操作的时间复杂度至O(n+q)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值