1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
| #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
const int N = 100010, MOD = 1e9 + 7, INF = 0x3f3f3f3f;
int n, m, a[N], comp[N], sum[N], deg[N], cnt, ans[N];
vi g[N], rg[N], g2[N], s;
bool vis[N];
void dfs(int u) {
vis[u] = true;
for (auto v : g[u])
if (!vis[v]) dfs(v);
s.push_back(u);
}
void rdfs(int u, int k) {
comp[u] = k;
sum[k] += a[u];
for (auto v : rg[u])
if (!comp[v]) rdfs(v, k);
}
void kosaraju() {
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
for (int i = s.size() - 1; i >= 0; i--)
if (!comp[s[i]]) rdfs(s[i], ++cnt);
}
void topo() {
queue<int> q;
for (int i = 1; i <= cnt; i++)
if (deg[i] == 0) q.push(i), ans[i] = sum[i];
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < g2[u].size(); i++) {
int v = g2[u][i];
deg[v]--;
ans[v] = max(ans[v], ans[u] + sum[v]);
if (deg[v] == 0) q.push(v);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data/in.txt", "r", stdin);
freopen("data/out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
rg[v].push_back(u);
}
kosaraju();
for (int i = 1; i <= n; i++)
for (int j = 0; j < g[i].size(); j++) {
if (comp[i] != comp[g[i][j]])
g2[comp[i]].push_back(comp[g[i][j]]), deg[comp[g[i][j]]]++;
}
topo();
cout << *max_element(ans + 1, ans + cnt + 1);
return 0;
}
|