P1135 奇怪的电梯
直接BFS广搜,搜上下可到达的楼层,继续压入起点搜索;搜到指定 层直接输出次数即可。
#include <bits/stdc++.h>
using namespace std;
int n, a, b, d[200 + 9];
bool vis[200 + 9];
int dx[] = {-1, 1};//向上和向下
struct node
{
int x, setp;//当前楼层,坐电梯的次数
};
queue <node> q;
int BFS(int x)
{
vis[a] = true;//标记起点
q.push({a, 0});//压入起点
while (! q.empty())
{
node cur = q.front();
q.pop();
if (cur.x == b)//到达目标b层
{
return cur.setp;
}
for (int i = 0; i < 2; i ++)
{
int nx = cur.x + dx[i] * d[cur.x];//向上/下走d[cur.x]步
if (nx >= 1 && nx <= n && vis[nx] == false)//可以走
{
vis[nx] = true;//标记走过
q.push({nx, cur.setp + 1});//压入新起点
}
}
}
return -1;
}
int main()
{
cin >> n >> a >> b;
for (int i = 1; i <= n; i ++)
{
cin >> d[i];
}
cout << BFS(a);
return 0;
}P5663 [CSP-J2019] 加工零件
算出所有到a的奇数路径和偶数路径,a的奇偶分别考虑。寻找到a的步数为 的路径是否存在即可。
#include <bits/stdc++.h>
using namespace std;
int n, m, q, dis[100000 + 9], dis2[100000 + 9];//dis[i]/dis2[i]表示1号节点到i号节点的长度为奇数/偶数的一条路径
vector <int> op[100000 + 9];
struct node
{
int x, step;//当前节点,步数
};
void bfs()
{
memset(dis, 0x3f, sizeof dis);//奇数路径清成最大值(要取最小值)
memset(dis2, 0x3f, sizeof dis2);//偶数路径清成最大值(要取最小值)
queue <node> q;
q.push({1, 0});
while (q.size())
{
node c = q.front();
q.pop();
for (int i = 0; i < op[c.x].size(); i ++)//所有可以走的节点
{
int v = op[c.x][i];
if ((c.step + 1) % 2 == 1)//当前走的是奇数路径
{
if (c.step + 1 < dis[v])//更优的奇数路径
{
dis[v] = c.step + 1;
q.push({v, c.step + 1});//压入新起点
}
}
else//当前走的是偶数路径
{
if (c.step + 1 < dis2[v])//更优的偶数路径
{
dis2[v] = c.step + 1;
q.push({v, c.step + 1});//压入新起点
}
}
}
}
}
int main()
{
cin >> n >> m >> q;
for (int i = 1; i <= m; i ++)
{
int x, y;
cin >> x >> y;
op[x].push_back(y);//无向图
op[y].push_back(x);
}
bfs();
while (q --)
{
int a, l;
cin >> a >> l;
if (l % 2 == 1)
{
if (dis[a] > l)//不能走到
{
cout << "No\n";
}
else
{
cout << "Yes\n";
}
}
else
{
if (dis2[a] > l)//不能走到
{
cout << "No\n";
}
else
{
cout << "Yes\n";
}
}
}
return 0;
}