您的位置:首页 > 其它

【BFS/Dijkstra】hdu 1548 A Strange Lift

2013-06-22 14:26 405 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: