码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3592 Instantaneous Transference(强连通+DP)

时间:2014-10-21 12:16:25      阅读:193      评论:0      收藏:0      [点我收藏+]

标签: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)

标签:style   http   color   io   os   ar   for   sp   on   

原文地址:http://blog.csdn.net/accelerator_/article/details/40342523

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!