HDU-4255 BFS 最短路

题意:蛇形填数,然后素数处是障碍,给你起点终点,求步数;

思路:其实就是bfs,关键是将数字转换成位置比较难;

bfs其实比较简单,就是固定的思路,固定的步骤;

模板:

 const int dir[][] = {{-, }, {, }, {, }, {, -}};
int vis[maxn], d[maxn];
bool is_ok(int x, int y)///坐标是否合格,按照题意来进行
{
if(x< || y<||x>n||y>n)
return false;
return true;
}
int dfs(Node st,Node ed)///起点终点
{
queue<Node> q;
q.push(st);///压进起点
memset(vis,,sisteof(vis));
memset(d,,sizeof(d));
int ss = a[st.x][st.y];
d[ss] = ;
int edd = a[ed.x][ed.y];
while(!q.empty())
{
Node c = q.front(),v;
q.pop();
int stt = a[c.x][c.y];
if(stt == edd)///先判断是否到达终点
return d[stt];
repu(i,,)
{
v.x = c.x + dir[i][];
v.y = c.y + dir[i][];
if(is_ok(v.x,v.y))///坐标是否合格
{
int sd = a[v.x][v.y];
if(!vis[sd])///符合所有条件后
{
q.push(v);///压进
vis[sd] = ;///V过
d[sd] = d[stt] + ;///步数为之前的+1
}
}
else
continue;
}
}
return -;
}

该题代码

 #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
#include<queue>
#include <set>
#define repu(i,a,b) for(int i=a;i<b;i++)
using namespace std;
#define N 1000010
#define ll long long
#define _cle(m, a) memset(m, a, sizeof(m))
const int maxn = ;
const int mn = ;
int tot;
int a[][];
struct Node
{
int x, y;
} nodes[maxn];
void init()
{
memset(a, , sizeof(a));
a[mn][mn] = ;
tot = ;
nodes[].x = mn;
nodes[].y = mn;
int cur = ;
int i = mn, j = mn+;
while(tot <= maxn)
{
int t;
t = ;
i++;
while(t < cur*)
{
a[--i][j] = ++tot;
nodes[tot].x = i;
nodes[tot].y = j;
t++;
}
t = ;
while(t < cur*)
{
a[i][--j] = ++tot;
nodes[tot].x = i;
nodes[tot].y = j;
t++;
}
t = ;
while(t < cur*)
{
a[++i][j] = ++tot;
nodes[tot].x = i;
nodes[tot].y = j;
t++;
}
t = ;
while(t < cur*)
{
a[i][++j] = ++tot;
nodes[tot].x = i;
nodes[tot].y = j;
t++;
}
++j;
cur++;
}
}
int prime[maxn];
void is_prime()
{
memset(prime, , sizeof(prime));
int m = sqrt(maxn+0.5);
prime[] = prime[] = ;
for(int i = ; i <= m; i++)
{
if(!prime[i])
{
for(int j = i*i; j <= maxn; j+=i)
{
prime[j] = ;
}
}
}
} const int dir[][] = {{-, }, {, }, {, }, {, -}};
int vis[maxn], d[maxn];
bool is_ok(int x, int y)
{
return x>= && y >=;
}
int bfs(Node z,Node b)
{
queue<Node> q;
q.push(z);
memset(vis,,sizeof(vis));
memset(d,,sizeof(d));
int ss = a[z.x][z.y];
d[ss] = ;
int ed = a[b.x][b.y];
while(!q.empty())
{
Node c = q.front(),v;
q.pop();
int st = a[c.x][c.y];
if(st == ed)
return d[st];
repu(i,,)
{
v.x = c.x + dir[i][];
v.y = c.y + dir[i][];
if(is_ok(v.x,v.y))
{
int sd = a[v.x][v.y];
if(!vis[sd]&&prime[sd])
{
q.push(v);
vis[sd] = ;
d[sd] = d[st] + ;
}
}
else
continue;
}
}
return -;
}
int main()
{
init();
is_prime();
int x, y, kase = ;
while(~scanf("%d%d", &x, &y))
{
if(!prime[x] || !prime[y])
{
printf("Case %d: impossible\n", ++kase);
continue;
}
int ans = bfs(nodes[x], nodes[y]);
if(ans == -) printf("Case %d: impossible\n", ++kase);
else printf("Case %d: %d\n", ++kase, ans);
} return ;
}
上一篇:List集合数据太多进行分批,List的subList方法应用


下一篇:spark的数据结构 RDD——DataFrame——DataSet区别