POJ 3278 Catch That Cow
题目链接:http://poj.org/problem?id=3278
题意:人在N,牛在K,人要去找牛,求最短路径。人在X,可以前往 X+1X−12×X 。
思路:裸BFS,直接搜即可。
代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;
const int N = 2e5 + 10;
const int INF = 0x3f3f3f3f;
typedef pair<int, int> P;
int dis[N];
int bfs(int s, int e) {
queue<P> q;
q.push(make_pair(s, 0));
while (!q.empty()) {
P u = q.front();
q.pop();
if (u.first == e) {
return u.second;
}
for (int i = -1; i <= 1; i += 2) {
P t;
t.first = u.first + i;
t.second = u.second + 1;
if (t.first >= 0 && t.first <= 2 * e && dis[t.first] > t.second) {
q.push(t);
dis[t.first] = t.second;
}
}
P v;
v.first = u.first * 2;
v.second = u.second + 1;
if (v.first >= 0 && v.first <= 2 * e && dis[v.first] > v.second) {
q.push(v);
dis[v.first] = v.second;
}
}
return -1;
}
int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
memset(dis, INF, sizeof(dis));
if (n >= k)
printf("%d\n", n - k);
else
printf("%d\n", bfs(n, k));
}
return 0;
}
POJ 2251 Dungeon Master
题目链接:http://poj.org/problem?id=2251
题意:三维空间,从S到T的最短路。
思路:裸BFS,直接搜。
代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 5e1 + 10;
struct Node {
int x, y, z;
int step;
};
int x[4] = {0, 1, 0, -1};
int y[4] = {1, 0, -1, 0};
int dis[N][N][N];
char _map[N][N][N];
int l, r, c;
bool inFiled(Node now) {
if (now.x >= 0 && now.x < r && now.y >= 0
&& now.y < c && now.z >= 0 && now.z < l)
return true;
return false;
}
int bfs(Node s) {
queue<Node> q;
q.push(s);
dis[s.x][s.y][s.z] = s.step;
while (!q.empty()) {
Node now = q.front();
q.pop();
if (_map[now.z][now.x][now.y] == 'E')
return now.step;
// cout << "now " << now.x << " " << now.y << " " << now.z << endl;
Node to;
for (int j = 0; j < 4; j++) {
to.x = now.x + x[j];
to.y = now.y + y[j];
to.z = now.z;
to.step = now.step + 1;
if (inFiled(to) && _map[to.z][to.x][to.y] != '#'
&& dis[to.z][to.x][to.y] > to.step) {
dis[to.z][to.x][to.y] = to.step;
q.push(to);
}
}
for (int i = -1; i <= 1; i++) {
to.x = now.x;
to.y = now.y;
to.z = now.z + i;
to.step = now.step + 1;
if (inFiled(to) && _map[to.z][to.x][to.y] != '#'
&& dis[to.z][to.x][to.y] > to.step) {
dis[to.z][to.x][to.y] = to.step;
q.push(to);
}
}
}
return -1;
}
int main() {
while (scanf("%d%d%d", &l, &r, &c) != EOF) {
if (!l && !r && !c)
break;
memset(dis, INF, sizeof(dis));
for (int i = 0; i < l; i++)
for (int j = 0; j < r; j++)
scanf("%s", _map[i][j]);
Node st;
for (int i = 0; i < l; i++) {
for (int j = 0; j < r; j++) {
for (int k = 0; k < c; k++) {
if (_map[i][j][k] == 'S') {
st.x = j, st.y = k, st.z = i;
st.step = 0;
}
}
}
}
int ans = bfs(st);
if (ans == -1)
printf("Trapped!\n");
else
printf("Escaped in %d minute(s).\n", ans);
}
return 0;
}