蓝桥杯 彩灯与任务

题目描述

输入样例

5 5

5 4 3 3 9

R 1

C 4

R 5

A 3

R 2

输出样例

5

3

3

思路

第一眼读不懂旋转是啥意思,根据样例连蒙带猜猜出来,其实就是把整个数组中的挪动几个位置。也很自然的按照题意写出来如下代码:

cpp 复制代码
#include <iostream>
using namespace std;
int N;
int A[1000];
int B[1000];
void rotate(int x){
  for(int i=0;i<N;i++){
    B[(i+x)%N]=A[i];
  }
   for(int i=0;i<N;i++){
    A[i]=B[i];
  }
}
int main()
{
  int M;
  cin>>N>>M;
  for(int i=0;i<N;i++){
    cin>>A[i];
  }
  char type;
  int num;
  int now = 0;
  while(M--){
    cin>>type>>num;
    if(type=='C'){ 
      rotate(N-num);
     }
    if(type=='A'){
        rotate(num);
    }
    if(type=='R'){
      cout<<A[(num-1)%N]<<endl;
    }
  }
  return 0;
}

正好有个拿过国一的大佬路过,他帮我改了,写出来如下代码 :

cpp 复制代码
#include <iostream>
using namespace std;
int N;
int A[1000];
int B[1000];
// void rotate(int x){
//   for(int i=0;i<N;i++){
//     B[(i+x)%N]=A[i];
//   }
//    for(int i=0;i<N;i++){
//     A[i]=B[i];
//   }
// }
int main()
{
  int M;
  cin>>N>>M;
  for(int i=0;i<N;i++){
    cin>>A[i];
  }
  char type;
  int num;
  int now = 0;
  while(M--){
    cin>>type>>num;
    if(type=='C'){
      now -= num;
    }
    if(type=='A'){
      now += num;
    }
    if(type=='R'){
      now %= N;
      cout<<A[(num - 1 - now + N)%N]<<endl;
    }
  }
  return 0;
}

可以看到,只需要记录下偏移量,不需要真正的偏移。强!

相关推荐
傅科摆 _ py11 小时前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
kiracrimson11 小时前
栈与队列容器:适配器、deque 与 priority_queue
开发语言·c++·适配器模式
Shaoshing11 小时前
LeetCode100 42.接雨水
java·算法·leetcode
域限奇点访客11 小时前
用AI生成问卷的网站怎么选?看题目录入结构、题型映射和生成后的校验
算法
qq_4663024512 小时前
如何通过部分文件名,读取出整个文件名
c++·qt
not coder12 小时前
一文讲通--从树到红黑树
数据结构·算法
octopus_c12 小时前
C++ 入门
开发语言·c++·算法
ZhengEnCi13 小时前
2026年10月30日AI早报:Gemini 4 Carbon登顶、DeepSeek融资1055亿、智元机器人上岗实测
人工智能·算法
强哥聊算力13 小时前
《算力江湖·Intel帝国往事》第三集:安迪·格鲁夫的铁血时代:Intel为什么能把对手逼到墙角?
运维·人工智能·科技·算法·ai·gpu算力
Shaoshing13 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode