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:
- Jump one box to the right.
- 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]]记录的是走到前一状态上一个相同数字的步数。