#include <cstdio>
#include <cstring>
#include <cctype>
#include <queue>
using namespace std;
#define check(x,y) x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&mp[x][y]!='*'
const int maxn = 50 + 10;
const int dir[4][2] = { -1, 0, 1, 0, 0, -1, 0, 1};
int n, m, T, w, t, kase, val[maxn], dis[maxn][maxn], step[maxn][maxn], ans, sum;
bool vis[maxn][maxn], res[maxn];
char mp[maxn][maxn];
void bfs(int x, int y, int s)
{
queue<int>Q;
Q.push(x * m + y);
vis[x][y] = 1, step[x][y] = 0;
while (!Q.empty())
{
int cur = Q.front(); Q.pop();
x = cur / m; y = cur % m;
for (int i = 0; i < 4; i++)
{
int Tx = x + dir[i][0], Ty = y + dir[i][1];
if (check(Tx, Ty))
{
vis[Tx][Ty] = 1;
step[Tx][Ty] = step[x][y] + 1;
if (mp[Tx][Ty] == '@') dis[s][0] = step[Tx][Ty];
if (isalpha(mp[Tx][Ty])) dis[s][mp[Tx][Ty] - '@'] = step[Tx][Ty];
if (mp[Tx][Ty] == '<') dis[s][w + 1] = step[Tx][Ty];
Q.push(Tx * m + Ty);
}
}
}
}
void dfs(int p, int s, int Time)
{
if (Time > t || ans == sum) return;
if (p > w && s > ans) ans = s;
for (int i = 0; i <= w + 1; i++)
if (dis[p][i] && !res[i])
{
res[i] = 1;
dfs(i, s + val[i], Time + dis[p][i]);
res[i] = 0;
}
}
int main(int argc, char const *argv[])
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d%d%d", &m, &n, &t, &w);
sum = 0, ans = -1; val[0] = val[w + 1] = 0;
memset(vis, 0, sizeof(vis));
memset(res, 0, sizeof(res));
memset(dis, 0, sizeof(dis));
for (int i = 1; i <= w; i++)
scanf("%d", &val[i]), sum += val[i];
for (int i = 0; i < n; i++)
scanf("%s", &mp[i]);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
memset(step, 0, sizeof(step));
memset(vis, 0, sizeof(vis));
if (mp[i][j] == '@') bfs(i, j, 0);
if (isalpha(mp[i][j])) bfs(i, j, mp[i][j] - '@');
if (mp[i][j] == '<') bfs(i, j, w + 1);
}
res[0] = 1;
dfs(0, 0, 0);
printf("Case %d:\n", ++kase);
if (ans >= 0) printf("The best score is %d.\n", ans);
else printf("Impossible\n");
if (T) printf("\n");
}
return 0;
}
迷宫中,起点到终点,有几个宝物,在给定的时间内,到达终点且能取得多少价值的宝物。
需要解决4个问题:
1、求入口到第一个取宝物的地方的最短距离
2、求第i个取宝物的地方到第i+1个取宝物的地方的最短距离
3、求第n个取宝物的地方到出口的最短距离
4、保证以上3点能在时间L内实现的情况下,取得的宝石价值最大
用bfs解决1-3,dfs求答案。