P3387 【模板】缩点
对原有向图缩点后的DAG在拓扑序上dp
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
const int N = 10000 + 10, M = 10000 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, m;
int w[N];
vector<int> G[N];
int dfn[N], low[N], times; // dfn时间戳
int sta[N], sz; // 手写栈,tarjan 时点入栈
bool insta[N]; // 标记是否在栈中
int belong[N], tot; // 强连通分量
int sum_w[N]; // 每个连通分量的w和
vector<int> newG[N]; // 缩点后新建图
int indeg[N]; // 缩点后新图的入度
int dp[N]; // dp
void tarjan(int u) {
dfn[u] = low[u] = ++times;
sta[++sz] = u;
insta[u] = true;
for (int v : G[u]) {
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (insta[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (low[u] == dfn[u]) {
tot++;
while (true) {
int top = sta[sz];
belong[top] = tot;
sum_w[tot] += w[top];
insta[top] = false;
sz--;
if (u == top) break;
}
}
}
void toposort() {
queue<int> q;
for (int i = 1; i <= tot; ++i) {
if (indeg[i] == 0) {
q.push(i);
dp[i] = sum_w[i];
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : newG[u]) {
indeg[v]--;
dp[v] = max(dp[v], dp[u] + sum_w[v]);
if (indeg[v] == 0) {
q.push(v);
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%d", &w[i]);
}
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
}
for (int i = 1; i <= n; ++i) {
if (!dfn[i]) {
tarjan(i);
}
}
for (int i = 1; i <= n; ++i) {
for (int v : G[i]) {
if (belong[i] != belong[v]) {
newG[belong[i]].push_back(belong[v]);
indeg[belong[v]]++;
}
}
}
toposort();
int ans = 0;
for (int i = 1; i <= tot; ++i) {
ans = max(ans, dp[i]);
}
printf("%d\n", ans);
return 0;
}