思维题 Corrupted Images

本文介绍了一个基于跳跃的游戏算法实现,玩家从第1个盒子出发,目标是到达第n个盒子。算法通过两种方式前进:每次向前跳一个盒子或跳到最近的同色盒子。文章详细解释了使用C++实现该算法的代码逻辑。

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

The goal of the game is to reach the nth box starting from the 1st box, by jumping between the boxes. The player can do one of the following jumps:

  1. Jump one box to the right.
  2. If the player stands at a box of color x, he/she can jump to the closest box of color x that is to the right of him, if such box exist.   

Input
3
6
9 2 4 7 1 5
5
1 2 1 1 4
6
1 2 3 1 3 2
Output
5
3
2


可以一步一步地跳,也可以一步跳到与当前石头数字一样的石头上(仅能跳到第一个相同数字的石头)。

#include<bits/stdc++.h>
using namespace std;

int n,T,a[200005],x,look[200005],ans[200005];
int main()
{
   scanf("%d",&T);
   while(T--)
   {
       memset(look,-1,sizeof(look));
       scanf("%d",&n);
       for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        ans[1]=0;
        look[a[1]]=0;
        for(int i=2;i<=n;i++)
           {
               if(look[a[i]]!=-1)
               {
                   ans[i]=min(ans[i-1]+1,look[a[i]]+1);
                   look[a[i]]=ans[i];
               }
               else
               {
                   ans[i]=ans[i-1]+1;
                   look[a[i]]=ans[i];
               }
           }
           printf("%d\n",ans[n]);
   }
}
当前状态可能是上一个石头跳过来的,也可能是上一个数字相同石头跳过来的。look[a[i]]!=-1,代表之前出现过a[i],look[a[i]]记录的是走到前一状态上一个相同数字的步数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值