5 1 5 3 3 1 2 5 0
3
第一眼看就知道应该要搜索,要不是放在最短路专题,还真想不到用图论做,简单题,刚好练习一下Spfa(看到Spfa时间效率不是很稳定,还是多用Dijkstra的好)
BFS占用内存少,运行快,代码少,如果是无权图还是用BFS写更好
BFS:
#include <cstdio> #include <cstring> #include <queue> using namespace std; struct Node { int num,step; Node(int nn=0,int ss=0) { num=nn,step=ss; } }u; const int INF=0x3f3f3f3f; int k[205]; int i,n,s,e,t,ans; bool vis[205]; void BFS() { queue<Node> q; q.push(Node(s,0)); vis[s]=true; while(!q.empty()) { u=q.front(); if(u.num==e) { ans=u.step; return ; } q.pop(); if((t=u.num+k[u.num])<=n&&!vis[t]) { vis[t]=true; q.push(Node(t,u.step+1)); } if((t=u.num-k[u.num])>0&&!vis[t]) { vis[t]=true; q.push(Node(t,u.step+1)); } } } int main() { while(scanf("%d",&n),n) { scanf("%d%d",&s,&e); for(i=1;i<=n;++i) scanf("%d",k+i); memset(vis,false,sizeof(vis)); ans=INF; BFS(); printf("%d\n",ans==INF?-1:ans); } return 0; }
Spfa:
#include <cstdio> #include <cstring> #include <queue> using namespace std; const int INF=0x3f3f3f3f; int k[205],w[205][205],dis[205]; int i,n,s,e,t,u,tmp; bool vis[205]; void Spfa() { queue<int> q; q.push(s); dis[s]=0; vis[s]=true; while(!q.empty()) { u=q.front(); q.pop(); vis[u]=false; for(i=1;i<=n;++i) if((tmp=dis[u]+w[u][i])<dis[i]&&!vis[i]) { dis[i]=tmp; vis[i]=true; q.push(i); } } } int main() { while(scanf("%d",&n),n) { scanf("%d%d",&s,&e); for(i=1;i<=n;++i) { scanf("%d",k+i); vis[i]=false; dis[i]=INF; } memset(w,0x3f,sizeof(w)); for(i=1;i<=n;++i) { if((tmp=i+k[i])<=n) w[i][tmp]=1; if(0<(tmp=i-k[i])) w[i][tmp]=1; } Spfa(); printf("%d\n",dis[e]==INF?-1:dis[e]); } return 0; }