HDU 1548 A strange lift(Dijkstra)
http://acm.hdu.edu.cn/showproblem.php?pid=1548
题意:
有一个N层的电梯,每层有一个数字k[i],表示你在第i层能通过按up按钮到i+k[i]层去,能通过按down按钮到i-k[i]层去.(当然如果i+k[i]或i-k[i]不属于[1,N]范围,那么你不能动)现在给你层号A和B,问你通过按电梯按钮,最少几次能从A到B.
分析:
其实这就是最短路问题.把每个楼层看成有向图的一个点,当第i层能通过按钮到达j层的时候,有一条i->j的距离为1的边.现在我们只需要求从A到B的最短距离即可.
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 1e9
using namespace std;
const int maxn=200+10;
struct Edge
{
int from,to,dist;
Edge(int f,int t,int d):from(f),to(t),dist(d){}
};
struct HeapNode
{
int d,u;
HeapNode(int d,int u):d(d),u(u){}
bool operator<(const HeapNode& rhs)const
{
return d>rhs.d;
}
};
struct Dijkstra
{
int n,m;
vector<Edge> edges;
vector<int> G[maxn];
bool done[maxn];
int d[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++) G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
m = edges.size();
G[from].push_back(m-1);
}
int dijkstra(int s,int e)
{
priority_queue<HeapNode> Q;
for(int i=0;i<n;i++) d[i]=INF;
d[s]=0;
memset(done,0,sizeof(done));
Q.push(HeapNode(d[s],s));
while(!Q.empty())
{
HeapNode x= Q.top(); Q.pop();
int u=x.u;
if(done[u]) continue;
done[u]=true;
for(int i=0;i<G[u].size();i++)
{
Edge &e=edges[G[u][i]];
if(d[e.to]>d[u]+e.dist)
{
d[e.to] = d[u]+e.dist;
Q.push(HeapNode(d[e.to],e.to));
}
}
}
if(d[e]==INF) return -1;
return d[e];
}
}DJ;
int main()
{
int n,s,e;
while(scanf("%d",&n)==1&&n)
{
scanf("%d%d",&s,&e);
s--,e--;
DJ.init(n);
for(int i=0;i<n;i++)
{
int k;
scanf("%d",&k);
if(i+k<n)
DJ.AddEdge(i,i+k,1);
if(i-k>=0)
DJ.AddEdge(i,i-k,1);
}
printf("%d\n",DJ.dijkstra(s,e));
}
return 0;
}