【BFS/Dijkstra】hdu 1548 A Strange Lift

51 篇文章 0 订阅
32 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=1548

效率比较:

BFS:

最短路径:


法一:BFS

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int NM=205;
int sx,sy,n,a[NM];
bool flag,vis[NM];
struct Node{
	int x,step;
};

void BFS()
{
	queue<Node>q1;
	Node t,pt;

	int temp;
	vis[sx]=1;
	t.x=sx;t.step=0;
	q1.push(t);
	while(!q1.empty()){
		t=q1.front();q1.pop();
		if(t.x==sy){
			flag=true;printf("%d\n",t.step);break;
		}
		pt.step=t.step+1;
		temp=t.x+a[t.x];
		if(!vis[temp] && temp<=n){
			pt.x=temp;vis[temp]=1;q1.push(pt);
		}
		temp=t.x-a[t.x];
		if(!vis[temp] && temp>0){
			pt.x=temp;vis[temp]=1;q1.push(pt);
		}
	}
}

int main()
{
	while(scanf("%d",&n) && n){
		scanf("%d%d",&sx,&sy);
		for(int i=1;i<=n;i++) scanf("%d",&a[i]);
		flag=false;
		memset(vis,0,sizeof(vis));
		BFS();
		if(!flag) printf("-1\n");
	}
	return 0;
}


法二:最短路径

#include<stdio.h>
#include<string.h>
const int NUM=0xfffff;
int a[205][205],f[205],d[205];
int main()
{
	int n,i,j,x,y,m,tt,MIN;
	while(scanf("%d",&n),n!=0)
	{
		for(i=1;i<=n;i++)
		{
			a[i][i]=0;
			for(j=1;j<i;j++)  //j<i
				a[i][j]=a[j][i]=NUM;
		}
		scanf("%d%d",&x,&y);
		for(i=1;i<=n;i++)
		{
			scanf("%d",&m);
			if(i+m<=n) a[i][i+m]=1;
			if(i-m>=1) a[i][i-m]=1;
		}
		for(i=1;i<=n;i++)
			d[i]=a[x][i];
		memset(f,0,sizeof(f));
		
		f[x]=1;
		for(i=2;i<=n;i++)
		{
			MIN=NUM;
			for(j=1;j<=n;j++)//找到要加入的最小的点
			{
				if(!f[j]&&d[j]<MIN)
				{tt=j;MIN=d[j];}
			}
			f[tt]=1;
			for(j=1;j<=n;j++)
			{
				if(!f[j]&&a[tt][j]+MIN<d[j])
					d[j]=a[tt][j]+MIN;
			}
		}
		if(d[y]<NUM) printf("%d\n",d[y]);
		else printf("-1\n");
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值