|
| 1 | +```cpp |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +int N, M, S, P; |
| 6 | +vector<vector<int>> g(500001), r(500001), rv(500001); |
| 7 | +bitset<500001> rt; |
| 8 | +bitset<500001> rest; |
| 9 | +bitset<500001> vis; |
| 10 | +int m[500001]{}, c[500001]{}, mn[500001]{}, d[500001]{}, dp[500001]{}; |
| 11 | +stack<int> st; |
| 12 | +set<pair<int, int>> ch; |
| 13 | + |
| 14 | +void dfs1(int n) { |
| 15 | + for (int i : g[n]) if (!vis[i]) { |
| 16 | + vis[i] = 1; |
| 17 | + dfs1(i); |
| 18 | + } |
| 19 | + st.push(n); |
| 20 | +} |
| 21 | + |
| 22 | +int dfs2(int n, int t) { |
| 23 | + c[n] = t; |
| 24 | + int sum = m[n]; |
| 25 | + for (int i : r[n]) if (!vis[i]) { |
| 26 | + vis[i] = 1; |
| 27 | + sum += dfs2(i, t); |
| 28 | + } |
| 29 | + return sum; |
| 30 | +} |
| 31 | + |
| 32 | +void dfs3(int n) { |
| 33 | + for (int i : rv[n]) { |
| 34 | + d[i]++; |
| 35 | + if (!vis[i]) { |
| 36 | + vis[i] = 1; |
| 37 | + dfs3(i); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +int main() { |
| 43 | + cin.tie(0)->sync_with_stdio(0); |
| 44 | + |
| 45 | + cin >> N >> M; |
| 46 | + for (int i = 0, a, b; i < M; i++) { |
| 47 | + cin >> a >> b; |
| 48 | + g[a].push_back(b); |
| 49 | + r[b].push_back(a); |
| 50 | + } |
| 51 | + for (int i = 1; i <= N; i++) cin >> m[i]; |
| 52 | + cin >> S >> P; |
| 53 | + for (int a; P--; rt[a] = 1) cin >> a; |
| 54 | + |
| 55 | + for (int i = 1; i <= N; i++) if (!vis[i]) { |
| 56 | + vis[i] = 1; |
| 57 | + dfs1(i); |
| 58 | + } |
| 59 | + vis.reset(); |
| 60 | + int cnt = 0; |
| 61 | + while (!st.empty()) { |
| 62 | + int n = st.top(); st.pop(); |
| 63 | + if (vis[n]) continue; |
| 64 | + cnt++; |
| 65 | + vis[n] = 1; |
| 66 | + mn[cnt] = dfs2(n, cnt); |
| 67 | + } |
| 68 | + |
| 69 | + for (int i = 1; i <= N; i++) { |
| 70 | + for (int j : g[i]) if (c[i] != c[j] && !ch.count(make_pair(c[i], c[j]))) { |
| 71 | + rv[c[i]].push_back(c[j]); |
| 72 | + ch.emplace(c[i], c[j]); |
| 73 | + } |
| 74 | + if (rt[i]) rest[c[i]] = 1; |
| 75 | + } |
| 76 | + |
| 77 | + queue<int> q; |
| 78 | + vis.reset(); |
| 79 | + dfs3(c[S]); |
| 80 | + q.push(c[S]); |
| 81 | + dp[c[S]] = mn[c[S]]; |
| 82 | + int ans = 0; |
| 83 | + while (!q.empty()) { |
| 84 | + int n = q.front(); q.pop(); |
| 85 | + if (rest[n]) ans = max(ans, dp[n]); |
| 86 | + for (int i : rv[n]) { |
| 87 | + dp[i] = max(dp[i], dp[n] + mn[i]); |
| 88 | + if (!--d[i]) q.push(i); |
| 89 | + } |
| 90 | + } |
| 91 | + cout << ans; |
| 92 | + |
| 93 | +} |
| 94 | +``` |
0 commit comments