POJ 3592 Instantaneous Transference(强连通+DP)

POJ 3592 Instantaneous Transference

题目链接

题意:一个图。能往右和下走,然后有*能够传送到一个位置。'#'不能走。走过一个点能够获得该点上面的数字值,问最大能获得多少

思路:因为有环先强连通缩点。然后问题转化为dag,直接dp就可以

代码:

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std; const int N = 1605;
const int d[2][2] = {0, 1, 1, 0}; int t, n, m, val[N];
char str[45][45];
vector<int> g[N], scc[N];
stack<int> S; int pre[N], dfn[N], dfs_clock, sccno[N], sccn, scc_val[N]; void dfs_scc(int u) {
pre[u] = dfn[u] = ++dfs_clock;
S.push(u);
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (!pre[v]) {
dfs_scc(v);
dfn[u] = min(dfn[u], dfn[v]);
} else if (!sccno[v]) dfn[u] = min(dfn[u], pre[v]);
}
if (dfn[u] == pre[u]) {
sccn++;
int sum = 0;
while (1) {
int x = S.top(); S.pop();
sum += val[x];
sccno[x] = sccn;
if (u == x) break;
}
scc_val[sccn] = sum;
}
} void find_scc() {
dfs_clock = sccn = 0;
memset(pre, 0, sizeof(pre));
memset(sccno, 0, sizeof(sccno));
for (int i = 0; i < n * m; i++)
if (!pre[i]) dfs_scc(i);
} int dp[N]; int dfs(int u) {
if (dp[u] != -1) return dp[u];
dp[u] = 0;
for (int i = 0; i < scc[u].size(); i++) {
int v = scc[u][i];
dp[u] = max(dp[u], dfs(v));
}
dp[u] += scc_val[u];
return dp[u];
} int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n * m; i++) g[i].clear();
for (int i = 0; i < n; i++)
scanf("%s", str[i]);
memset(val, 0, sizeof(val));
int a, b;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (str[i][j] == '#') continue;
if (str[i][j] >= '0' && str[i][j] <= '9') val[i * m + j] = str[i][j] - '0';
if (str[i][j] == '*') {
scanf("%d%d", &a, &b);
g[i * m + j].push_back(a * m + b);
}
for (int k = 0; k < 2; k++) {
int x = i + d[k][0];
int y = j + d[k][1];
if (x < 0 || x >= n || y < 0 || y >= m || str[x][y] == '#') continue;
g[i * m + j].push_back(x * m + y);
}
}
}
find_scc();
for (int i = 1; i <= sccn; i++) scc[i].clear();
for (int u = 0; u < n * m; u++) {
for (int j = 0; j < g[u].size(); j++) {
int v = g[u][j];
if (sccno[u] == sccno[v]) continue;
scc[sccno[u]].push_back(sccno[v]);
}
}
memset(dp, -1, sizeof(dp));
printf("%d\n", dfs(sccno[0]));
}
return 0;
}
上一篇:使用idea+gradle建立SSM项目


下一篇:1. CNN卷积网络-初识