我的思路是在由药、起点、终点构成的小图上面做操作以优化时间。我先写了一版DFS代码,T了,但是在小图上面跑DFS时加上一个判断能量的数组(只是单纯存了一个点的最大能量)优化就过了。
但是能量数组写成了尽量让到达这个点的能量小的代码,跑的飞快,全AC,为什么?
Code:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <set>
#include <map>
#include <time.h>
using namespace std;
int h, w, a[300][300];
char m[300][300];
int n;
int dis[400][400];
int x[400], y[400];
int dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0};
void bfs(int idx) {
int dist[300][300];
memset(dist, 0x3f, sizeof(dist));
dist[x[idx]][y[idx]] = 0;
queue<int> q;
q.push(x[idx]);
q.push(y[idx]);
while (q.size()) {
int nowx = q.front();
q.pop();
int nowy = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = nowx + dx[i], ny = nowy + dy[i];
if (nx >= 1 && nx <= h && ny >= 1 && ny <= w && dist[nx][ny] == 0x3f3f3f3f && m[nx][ny] != '#') {
dist[nx][ny] = dist[nowx][nowy] + 1;
q.push(nx);
q.push(ny);
}
}
}
for (int i = 1; i <= n + 2; i++) {
dis[idx][i] = dist[x[i]][y[i]];
}
}
bool vis[300][300];
int dis1[400];
void dfs(const int u, int t) {
if (t < dis1[u]) dis1[u] = t;
else return;
int p = x[u], q = y[u];
vis[x[u]][q] = 1;
if (p == x[2] && q == y[2]) {
cout << "Yes";
exit(0);
}
int tmp = a[p][q];
if (t < a[p][q] && a[p][q]) {
t = a[p][q], a[p][q] = 0;
}
for (int i = 1; i <= n + 2; i++) {
if ((x[i] != p || y[i] != q) && !vis[x[i]][y[i]] && t >= dis[u][i]) {
t -= dis[u][i];
dfs(i, t);
t += dis[u][i];
}
}
a[p][q] = tmp;
vis[p][q] = 0;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> h >> w;
for (int i = 1; i <= h; i++) {
for (int j = 1; j <= w; j++) {
cin >> m[i][j];
if (m[i][j] == 'S') {
x[1] = i, y[1] = j;
}
if (m[i][j] == 'T') {
x[2] = i, y[2] = j;
}
}
}
cin >> n;
for (int i = 1; i <= n; i++) {
int r, c, e;
cin >> r >> c >> e;
a[r][c] = e;
x[i + 2] = r, y[i + 2] = c;
}
for (int i = 1; i <= n * 2; i++) {
bfs(i);
}
memset(dis1, 0x3f, sizeof(dis1));
dfs(1, 0);
cout << "No";
return 0;
}