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

樣例輸出

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章