强连通分量+记忆化搜索题。一开始看成迷宫类搜索题,没想到这种题原来也可以是强连通分量题Orz,涨姿势了。题意:故事背景就是红警里面的超时空矿车采矿,起点和基地是这个迷宫图的左上角的格子。每一个格子要么是数字要么是*或者#,如果是数字代表这里有这个数字数量的矿,如果是#说明这个格子是石头,无法到达,保证基地和起点不会是石头,如果是*说明这里有一个传送装置,你可以选择传送到指定位置。超时空矿车随时都可以瞬移至基地,并且超时空矿车每走一步只能往下或者往右两个方向走。现在问这个超时空矿车从起点出动一次,最多可以采多少矿回来?
我的解题思路:差点就用裸搜索去做了,后来看了题解才发现这是强连通图。首先要建图,每一个点都有一个编号,这个编号可以是i*m+j,这样节点编号就是从0~n*m-1了。先把图输入进来,然后开始建图,按照从左至右从上至下的顺序一次读取点的信息并建边,如果是石头那就不要建边,另外建边只能建右边的点和下面的点,注意边界情况。如果读取的点是有传送装置点不要忘了输入传送坐标并且多建一条边连接传送到的点。这样,每一个点都读取完那么图也建完了。最后就是强连通缩点重建强连通图,题目要求其实就是求这个强连通图的最长路,用记忆化搜索解决。注意:因为起点是确定的,所以只需要从起点开始记忆化搜索一遍就可以直接得到答案了。求的是起点确定的最长路而不是整个图的最长路。友情提示:正因为起点是确定的,所以也可以不用记忆化搜索直接从起点DFS来求得答案也可以。
我的解题代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 2000;
const int M = 42;
char map[M][M];
vector<int> e[N];
vector<int> scce[N]; //强连通图
int dfn[N], low[N];
int stack[N], stop;
bool instack[N];
int timer, sccn;
int belong[N];
int w[N], sccw[N]; //点权与强连通分量权
int dp[N];
int n, m, t;
void InitRead();
void DataProcess();
void Tarjan(int x);
void Dfs(int x);
inline int ID(int x, int y) //根据坐标获取点的编号
{
return x * m + y;
}
int main()
{
scanf("%d", &t);
while (t--)
{
InitRead();
DataProcess();
}
return 0;
}
void InitRead()
{
stop = timer = sccn = 0;
memset(dfn, 0, sizeof(dfn));
memset(instack, false, sizeof(instack));
memset(dp, -1, sizeof(dp));
memset(w, 0, sizeof(w));
for (int i=0; i<N; ++i)
{
e[i].clear();
scce[i].clear();
}
scanf("%d %d", &n, &m);
for (int i=0; i<n; ++i)
{
scanf("%s", map[i]);
}
int x, y, id;
for (int i=0; i<n; ++i) //建图
{
for (int j=0; j<m; ++j)
{
if (map[i][j] == '#') continue;
id = ID(i, j);
if (i != n - 1 && map[i+1][j] != '#')
{
e[id].push_back(ID(i+1, j));
}
if (j != m - 1 && map[i][j+1] != '#')
{
e[id].push_back(ID(i, j+1));
}
if (map[i][j] == '*')
{
scanf("%d %d", &x, &y);
e[id].push_back(ID(x, y));
}
else
{
w[id] = map[i][j] - '0';
}
}
}
return;
}
void DataProcess()
{
int sum = n * m; //节点数量
for (int i=0; i<sum; ++i)
{
if (!dfn[i]) Tarjan(i);
}
for (int i=0; i<sum; ++i) //重建强连通图
{
int size = e[i].size();
for (int j=0; j<size; ++j)
{
if (belong[i] != belong[e[i][j]])
{
scce[belong[i]].push_back(belong[e[i][j]]);
}
}
}
Dfs(belong[ID(0, 0)]); //记忆化搜索起点所属的强连通分量
printf("%d\n", dp[belong[ID(0, 0)]]);
return;
}
void Tarjan(int x)
{
dfn[x] = low[x] = ++timer;
stack[stop++] = x;
instack[x] = true;
int size = e[x].size();
int y;
for (int i=0; i<size; ++i)
{
y = e[x][i];
if (!dfn[y])
{
Tarjan(y);
low[x] = min(low[x], low[y]);
}
else if (instack[y])
{
low[x] = min(low[x], dfn[y]);
}
}
if (dfn[x] == low[x])
{
sccn++;
int temp = 0;
do
{
y = stack[--stop];
instack[y] = false;
belong[y] = sccn;
temp += w[y];
} while (x != y);
sccw[sccn] = temp;
}
return;
}
void Dfs(int x)
{
int size = scce[x].size();
if (size == 0) dp[x] = sccw[x];
for (int i=0; i<size; ++i)
{
if (dp[scce[x][i]] == -1) Dfs(scce[x][i]);
dp[x] = max(dp[x], dp[scce[x][i]] + sccw[x]);
}
return;
}