题目地址
http://bailian.openjudge.cn/practice/4105/
Code
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <map>
#include <vector>
#include <math.h>
#include <algorithm>
#define INF 0x3fffffff
#define N 250
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
using namespace std;
typedef long long LL;
struct Node {
int x, y;
int step;
int baoshi;
Node (int xx, int yy, int ss, int bb) {
x = xx;
y =yy;
step = ss;
baoshi = bb;
}
bool operator < (const Node &b) const {
return step > b.step;
}
};
int n, m, k;
char a[N][N];
bool v[N][N][1<<5];
bool C(int x, int y) {
if (0 <= x && x < n && 0 <= y && y < m) {
return true;
} else {
return false;
}
}
int get_baoshi(int x) {
int ans = 0;
while (x > 0) {
ans += (x) & 0x1;
x >>= 1;
}
return ans;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#else
//
#endif
int t;
cin >> t;
for (int i = 0; i < t; i++) {
cin >> n >> m >> k;
memset(a, 0, sizeof(a));
memset(v, 0, sizeof(v));
int sx, sy, ex, ey;
int cx[20];
int cy[20];
int ci = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
if (a[i][j] == 'S') {
sx = i;
sy = j;
} else if (a[i][j] == 'E') {
ex = i;
ey = j;
} else if (a[i][j] == '$') {
cx[ci] = i;
cy[ci] = j;
ci++;
}
}
}
priority_queue<Node> q;
int flag = 0;
q.push(Node(sx, sy, 0, 0));
v[sx][sy][0] = 1;
while(!q.empty()) {
Node cur = q.top();
q.pop();
if (cur.x == ex && cur.y == ey && (get_baoshi(cur.baoshi) >= k)) {
printf("%d\n", cur.step);
flag = 1;
break;
} else if (cur.x == ex && cur.y == ey && (get_baoshi(cur.baoshi) < k)) {
continue;
}
for (int i = 0; i < 4; i++) {;
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if (!C(nx, ny)) continue;
if (a[nx][ny] == '#') continue;
int baoshi = cur.baoshi;
if ('0' <= a[nx][ny] && a[nx][ny] <= '4') {
baoshi |= 1 << (a[nx][ny]-'0');
}
if (v[nx][ny][baoshi]) continue;
v[nx][ny][baoshi] = 1;
if (a[nx][ny] == '$') {
for (int i = 0; i < ci; i++) {
nx = cx[i];
ny = cy[i];
if (v[nx][ny][baoshi]) continue;
v[nx][ny][baoshi] = 1;
q.push(Node(nx, ny, cur.step+1, baoshi));
}
}
q.push(Node(nx, ny, cur.step+1, baoshi));
}
}
if (flag == 0) {
printf("oop!\n");
}
}
return 0;
}