POJ 3592 Instantaneous Transference(強連通+DP)

來源:互聯網
上載者:User

標籤:style   http   color   io   os   ar   for   sp   on   

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;}


POJ 3592 Instantaneous Transference(強連通+DP)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.