hdu 1548 A strange lift
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1548
本题为简单最短路,构图方法为如果在第i层可以上升Ki层则增加边i - >(i+Ki) 否则不加边,如果可以下降Ki层则增加边i-> (i - Ki)
#include<iostream> #include<queue> #include<string> using namespace std; #define maxn 205 #define INF (1<<30) struct node { int v; node *next; }*head[maxn],edge[maxn*maxn]; int n,dis[maxn]; bool vis[maxn]; void spfa(int start) { for(int i = 0; i <= n; i++) dis[i] = INF; memset(vis,false,sizeof(vis)); vis[start] = true; dis[start] = 0; queue<int>que; que.push(start); while(!que.empty()) { int now = que.front(); vis[now] = true; que.pop(); for(node *p = head[now]; p; p = p->next) { if(dis[p->v] > dis[now] + 1) { dis[p->v] = dis[now] + 1; if( !vis[p->v]) { vis[p->v] = true; que.push(p->v); } } } } } int main() { int s,e,i,K; while(cin >> n,n) { cin >> s >> e; for( i = 0; i <= n; i++) head[i] = NULL; node *p = edge; for(i = 1; i <= n; i++) { scanf("%d",&K); if(i - end >= 1)//如果可以下降K层则增加边i -> i - K { p->v = i - K; p->next = head[i]; head[i] = p++; } if(i + end <= n) //如果可以上升K层则增加边i -> i+K { p->v = i + K; p->next = head[i]; head[i] = p++; } } spfa(s); if(dis[e] == INF) printf("-1\n"); else printf("%d\n",dis[e]); } return 0; }