Description
在数轴上给出n个坐标以及机器人的位置,机器人每次会左移或右移到相邻坐标,如果不能移动就不移动,五种操作
print:输出机器人当前位置坐标
moveLeft:机器人左移一步
moveRight:机器人右移一步
insertLeft x:往机器人左边位置插入x
insertRight x :往机器人右边位置插入x
Input
第一行两个整数n和p分别表示坐标数量和机器人当前位置(第p个坐标),之后n个整数表示这n个坐标,然后输入一整数q表示操作数,最后q行每行一种操作
Output
对于每次print操作,输出机器人当前位置坐标
Sample Input
3 2
2 3 5
15
moveLeft
insertLeft 1
moveLeft
print
moveLeft
moveRight
print
moveRight
insertRight 4
moveRight
moveRight
print
moveRight
moveLeft
print
Sample Output
1
2
5
4
Solution
维护一个双端链表即可
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
typedef struct node
{
node *pre,*next;
int v;
}*list;
int n,pos,Q;
void insert(list a,list b,list c)
{
a->next=b,b->pre=a,b->next=c,c->pre=b;
}
int main()
{
while(~scanf("%d%d",&n,&pos))
{
list head,tail,p,q;
head=(list)malloc(sizeof(node));
head->pre=NULL;
tail=(list)malloc(sizeof(node));
tail->next=NULL;
head->next=tail,tail->pre=head;
p=head;
for(int i=1;i<=n;i++)
{
int temp;
scanf("%d",&temp);
q=(list)malloc(sizeof(node));
q->v=temp;
insert(p,q,tail),p=q;
}
p=head;
while(pos--)p=p->next;
scanf("%d",&Q);
while(Q--)
{
char op[10];
int x;
scanf("%s",op);
if(op[0]=='p')printf("%d\n",p->v);
else if(op[4]=='L')
{
if(p->pre->pre!=NULL)p=p->pre;
}
else if(op[4]=='R')
{
if(p->next->next!=NULL)p=p->next;
}
else if(op[6]=='L')
{
scanf("%d",&x);
q=p->pre;
list temp=(list)malloc(sizeof(node));
temp->v=x;
insert(q,temp,p);
}
else
{
scanf("%d",&x);
q=p->next;
list temp=(list)malloc(sizeof(node));
temp->v=x;
insert(p,temp,q);
}
}
}
return 0;
}