2016 CCPC 东北赛落幕了,结果很不理想。痛定思痛,究其原因还是个人实力太弱,要完成计划还是不能太过依靠队友。努力练吧,从头开始,仔仔细细从头学过。下次,一个人参赛吧。
回到这题,求最短路径,裸的bfs模板。bfs特性是就是返回一个最短的路径。
两种方式,一种STL,一种队列模拟。
STL容器():
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<map>
#include<cmath>
using namespace std;
const int maxn = 100005;
bool vis[maxn];
int step[maxn];
int n,k;
int dir[2]={1,-1};
bool judge(int x)
{
if(x>=0&&x<=100000&&!vis[x])
return 1;
return 0;
}
int bfs()
{
memset(vis,0,sizeof(vis));
vis[n]=1;
queue<int>q;
q.push(n);
step[n]=0;
while(!q.empty())
{
int cur=q.front();
q.pop();
for(int i=0;i<3;i++)
{
if(i<2)
{
int nxt = cur+dir[i];
if(judge(nxt))
{
q.push(nxt);
step[nxt]=step[cur]+1;
vis[nxt]=1;
}
if(nxt==k)return step[nxt];
}
else
{
int nxt = cur*2;
if(judge(nxt))
{
q.push(nxt);
step[nxt]=step[cur]+1;
vis[nxt]=1;
}
if(nxt==k)return step[nxt];
}
}
}
return -1;
}
int main()
{
while(cin>>n>>k)
cout<<bfs()<<endl;
}
队列模型和queue在bfs的实现是等效的。
数组:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
int x,step;
}q[100005];
bool vis[100005];
int dir[2]={1,-1};
bool judge(int x)
{
if(x>=0&&x<=100000&&!vis[x])return 1;
return 0;
}
int bfs(int n,int k)
{
memset(vis,0,sizeof(vis));
vis[n]=1;
int front = 0,rear = 1;
q[front].x=n;
q[front].step=0;
while(front<rear)
{
node now = q[front++];
for(int i=0;i<3;i++)
{
if(i<2)
{
node cur = now;
cur.x = now.x+dir[i];
if(judge(cur.x))
{
vis[cur.x]=1;
q[rear].x=cur.x;
q[rear++].step=cur.step+1;
}
}
else
{
node cur = now;
cur.x = now.x*2;
if(judge(cur.x))
{
vis[cur.x]=1;
q[rear].x=cur.x;
q[rear++].step=cur.step+1;
}
}
if(now.x==k)return now.step;
}
}
}
int main()
{
int n,k;
while(cin>>n>>k)
cout<<bfs(n,k)<<endl;
}
道路且险且远,吾自以此为戒。