GYM 100090 J.Product Innovation(链表)

本文介绍了一个基于双端链表实现的机器人坐标移动问题解决方案。具体包括读取坐标数据、处理多种移动指令(如左移、右移、插入等),并输出机器人在数轴上的实时位置。通过C++代码示例详细展示了如何高效地进行这些操作。

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

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值