题目链接
题意:给定一个有向图,每个点有权值(可能为负),现在要求一条路径,走过每个点可以选择获得或或得该点权值,一个点最多获得一次,问一条最大值的路
思路:图有环,所以先缩点,然后就是DAG最长路了,dp搞搞就可以了
代码:
#include <cstdio> #include <cstring> #include <vector> #include <map> #include <algorithm> #include <stack> using namespace std; const int N = 30005; int n, m, val[N]; vector<int> g[N], scc[N]; #define MP(a,b) make_pair(a,b) typedef pair<int, int> pii; map<pii, int> vis; stack<int> S; int pre[N], dfn[N], dfs_clock, sccn, sccno[N], 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 (pre[u] == dfn[u]) { sccn++; int sum = 0; while (1) { int x = S.top(); S.pop(); if (val[x] > 0) sum += val[x]; sccno[x] = sccn; if (x == u) 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; 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() { while (~scanf("%d%d", &n, &m)) { vis.clear(); for (int i = 0; i < n; i++) { scanf("%d", &val[i]); g[i].clear(); } int u, v; while (m--) { scanf("%d%d", &u, &v); g[u].push_back(v); } find_scc(); for (int i = 1; i <= sccn; i++) scc[i].clear(); for (int u = 0; u < n; u++) { for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; pii tmp = MP(u, v); if (sccno[u] == sccno[v] || vis.count(tmp)) continue; vis[tmp] = 1; scc[sccno[u]].push_back(sccno[v]); } } int ans = 0; memset(dp, -1, sizeof(dp)); for (int i = 1; i <= sccn; i++) ans = max(ans, dfs(i)); printf("%d\n", ans); } return 0; }