Poj 3592 instantaneous transference
Question Link
Question: A graph can go to the right and down, And then * can be transferred to a position. '#' cannot go. After walking through a point, you can obtain the number value above the point, how much can be obtained
Idea: because there is a strong link contraction point in a ring, and then the problem is converted to Dag, directly DP.
Code:
#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;}
Poj 3592 instantaneous transference (strong connectivity + dp)