1422. 步行(walk)

1422. 步行(walk)

题目描述

ftiasch 又开发了一个奇怪的游戏,这个游戏是这样的:有N 个格子排成一列,每个格子上有一个数字,第i 个格子的数字记为Ai。这个游戏有2 种操作:

  1. 如果现在在第i 个格子,则可以跳到第Ai 个格子。

  2. 把某个Ai 增加或减少1。

nm 开始在第1 个格子,他需要走到第N 个格子才能通关。现在他已经头昏脑涨啦,需要你帮助他求出,从起点到终点最少需要多少次操作。

输入

第1 行,1 个整数N。
第2 行,N 个整数Ai。

输出

1 行,1 个整数,表示最少的操作次数。

样例输入

5
3 4 2 5 3

样例输出

扫描二维码关注公众号,回复: 11331094 查看本文章
3

数据范围限制

对于30% 的数据,1<= N<=10。
对于60% 的数据,1<= N<= 1 000。
对于100% 的数据,1 <=N<=100000,1 <=Ai<=N。

对于本题大意,我一直理解错了一点,认为第2种操作不可以连续使用,其实是可以的。

50分(dfs):
超时!

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#define fre(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout);
using namespace std;
const int MAX=2147483647;
const int N=1e5+10;
int n,a[N],f[N];
void input()
{
	memset(f,127/3,sizeof(f));
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
}
void dfs(int x,int step)
{
	if(x==n) 
	{
		f[n]=min(f[n],step);
		return;
	}
	if(f[x]<=step) return;
	f[x]=step;
	dfs(a[x],step+1);
	if(a[x]+1>=1&&a[x]+1<=n) dfs(a[x]+1,step+2);
	if(a[x]-1>=1&&a[x]-1<=n) dfs(a[x]-1,step+2);
}
int main()
{
	fre(walk);
	input();
	dfs(1,0);
	printf("%d",f[n]);
	return 0;
}

100分(bfs)
可参照机器人搬重物
我们要把第2种操作当成一个“点“加入队列,注意队列的数组要开大一点,有三种状态!!

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#define fre(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout);
using namespace std;
const int MAX=2147483647;
const int N=1e5+10;
int n,a[N],p[4*N][3];
bool vis[N];
void bfs()
{
	p[1][0]=1,vis[1]=1;
	int head=0,tail=1;
	while(head<=tail)
	{
		head++;
		int f=p[head][1],tx=p[head][0]+f,step=p[head][2];
		if(p[head][0]==n) {printf("%d",step);return;}
		if(!f)
		{
			if(!vis[a[tx]])
			{
				tail++;
				p[tail][0]=a[tx],p[tail][2]=step+1;
				vis[a[tx]]=1;
			}
			if(1<=a[tx]+1&&a[tx]+1<=n&&(!vis[a[tx]+1]))
			{
				tail++;
				p[tail][0]=a[tx],p[tail][1]=1,p[tail][2]=step+1;
			}
			if(1<=a[tx]-1&&a[tx]-1<=n&&(!vis[a[tx]-1]))
			{
				tail++;
				p[tail][0]=a[tx],p[tail][1]=-1,p[tail][2]=step+1;
			}	
		}
		else
		{
			if(!vis[tx])
			{
				tail++;
				p[tail][0]=tx,p[tail][2]=step+1;
				vis[tx]=1;
			}
			if(1<=tx+1&&tx+1<=n&&(!vis[tx+1]))
			{
				tail++;
				p[tail][0]=tx,p[tail][1]=1,p[tail][2]=step+1;
			}
			if(1<=tx-1&&tx-1<=n&&(!vis[tx-1]))
			{
				tail++;
				p[tail][0]=tx,p[tail][1]=-1,p[tail][2]=step+1;
			}
		}
		 
	}
}
int main()
{
	fre(walk);
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/bigwinner888/article/details/105981706