bzoj1179 [Apio2009]Atm
Description
\(n, m \leqslant 500000\)。
Solution
直接在原图上SPFA跑最长路肯定要GG(因为有环)。tarjan缩点后再跑SPFA就没事了。
#include<bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, flag = 1; char ch = getchar();
while (ch > '9' || ch < '0') { if (ch == '-') flag = -1; ch = getchar(); }
while (ch <= '9' && ch >= '0') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * flag;
}
#define N 500001
#define rep(ii, aa, bb) for (int ii = aa; ii <= bb; ii++)
#define fech(i, x) for (int i = 0; i < x.size(); i++)
#define INF 0x7fffffff
int n, m;
vector<int> g[N];
struct edge { int u, v; }e[N];
int mny[N];
bool isBar[N];
int ind, low[N], dfn[N];
stack<int> stk;
bool inStk[N];
int belong[N];
int scc;
vector<int> sccHave[N];
vector<int> sccG[N];
int sccMny[N];
int dis[N];
void tarjan(int u) {
dfn[u] = low[u] = ++ind;
stk.push(u);
inStk[u] = 1;
fech(i, g[u]) {
int v = g[u][i];
if (!dfn[v]) tarjan(v), low[u] = min(low[u], low[v]);
else if (inStk[v]) low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u]) {
scc++;
int v;
do {
v = stk.top(); stk.pop(); inStk[v] = 0;
belong[v] = scc; sccHave[scc].push_back(v); sccMny[scc] += mny[v];
} while (u != v);
}
}
queue<int> q;
bool vis[N];
void spfa(int S) {
rep(i, 1, scc) dis[i] = -INF;
dis[S] = sccMny[S], vis[S] = 1, q.push(S);
while (q.size()) {
int u = q.front(); q.pop(), vis[u] = 0;
fech(i, sccG[u]) {
int v = sccG[u][i];
if (dis[v] < dis[u] + sccMny[v]) {
dis[v] = dis[u] + sccMny[v];
if (!vis[v]) q.push(v), vis[v] = 1;
}
}
}
}
int main() {
n = read(); m = read();
rep(i, 1, m) { int u = read(), v = read(); g[u].push_back(v); e[i].u = u, e[i].v = v; }
rep(i, 1, n) mny[i] = read();
rep(i, 1, n) if (!dfn[i]) tarjan(i);
rep(i, 1, m) if (belong[e[i].u] != belong[e[i].v]) sccG[belong[e[i].u]].push_back(belong[e[i].v]);
spfa(belong[read()]);
int P = read(), ans = -INF;
while (P--) ans = max(ans, dis[belong[read()]]);
cout << ans;
return 0;
}