P1563 玩具谜题(模拟)

题的链接:P1563 玩具谜题

题解: 四种情况(具体两种),即顺时针还是逆时针;以防止b太大,我用了while循环,(题目好像 b 并不大);

参考代码1.0: res从1开始的。。。
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAX 20010
using namespace std;

int N, M, a, b, res = 1;
int dir[100010];
string str[100010];

int main()
{
    cin >> N >> M;
    for(int i = 1; i <= N; i++) cin >> dir[i] >> str[i];
    for(int i = 0; i < M; i++)
    {
        cin >> a >> b;
        int t = res;
        if(a == 0)// 左
        {
            if(dir[t] == 0)//朝内
            {
                res -= b;
                while(res <= 0) res += N;
            }
            else//朝内
            {
                res += b;
                while(res > N) res -= N;
            }
        }
        else//右
        {
            if(dir[t] == 0)//朝内
            {
                res += b;
                while(res > N) res -= N;
            }
            else//朝内
            {
                res -= b;
                while(res <= 0) res += N;
            }
        }
    }
    cout << str[res];
    return 0;
}

参考代码2.0: 代码优化版,看了这个代码才发现,每次移动的步骤不会超出人数大小。。。若超出取余后一定会成为负数。。。。考虑的多了。
  • 逆时针时:直接(res + b)% N, res从0开始
  • 顺时针时:先 - b ,再 +N,再 %N; (b 看来不会太大, 否则就直接取余成负数了)
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAX 20010
using namespace std;

int N, M, a, b, res;
int dir[100010];
string str[100010];

int main()
{
    cin >> N >> M;
    for(int i = 0; i < N; i++) cin >> dir[i] >> str[i];
    for(int i = 0; i < M; i++)
    {
        cin >> a >> b;
        //左 朝内
        if(a == 0 && dir[res] == 0) res = (res + N - b) % N;
        else if(a == 0 && dir[res] == 1) res = (res + b) % N;
        else if(a == 1 && dir[res] == 0) res = (res + b) % N;
        else if(a == 1 && dir[res] == 1) res = (res + N - b) % N;
    }
    cout << str[res];
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值