이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
// 22.48
#include <bits/stdc++.h>
using namespace std;
const int DIM = 1000005;
long long dst[DIM];
int oki[DIM], lev[DIM], cst[DIM], fth[DIM];
vector<int> cyc, val;
vector<long long> dpl, dpr;
vector<pair<int, int>> edg[DIM];
void dfs1(int x, int f) {
oki[x] = true; lev[x] = lev[f] + 1;
bool ok = false;
for (auto it : edg[x]) {
int y = it.first, c = it.second;
if (!oki[y]) {
cst[y] = c; fth[y] = x; dfs1(y, x); }
else if (lev[y] < lev[x] and (y != f or ok)) {
for (int z = x; z != fth[y]; z = fth[z]) {
oki[z] = 2; cyc.push_back(z);
if (z == y) {
val.push_back(c); }
else {
val.push_back(cst[z]); } } }
if (y == f) {
ok = true; } } }
void dfs2(int x, int f, int &nd, long long &ds) {
if (ds < dst[x]) {
ds = dst[x]; nd = x; }
for (auto it : edg[x]) {
int y = it.first, c = it.second;
if (oki[y] == 2 or y == f) {
continue; }
dst[y] = dst[x] + c; dfs2(y, x, nd, ds); } }
int main(void) {
#ifdef HOME
freopen("islands.in", "r", stdin);
freopen("islands.out", "w", stdout);
#endif
int n; cin >> n;
for (int i = 1; i <= n; ++i) {
int y, c; cin >> y >> c;
edg[i].push_back(make_pair(y, c));
edg[y].push_back(make_pair(i, c)); }
long long ans = 0;
for (int k = 1; k <= n; ++k) {
if (oki[k]) {
continue; }
cyc.clear(); val.clear(); dfs1(k, 0);
long long aux = 0; int m = cyc.size();
dpl.resize(m); dpr.resize(m);
dpl[0] = 0;
for (int i = 1; i < m; ++i) {
dpl[i] = dpl[i - 1] + val[i - 1]; }
dpr[m - 1] = val[m - 1];
for (int i = m - 2; i >= 0; --i) {
dpr[i] = dpr[i + 1] + val[i]; }
long long cs1 = -1LL << 60, cs2 = -1LL << 60;
for (int i = 0; i < m; ++i) {
int x = cyc[i]; oki[x] = 1;
int c1; long long mx1 = -1; dst[x] = 0; dfs2(x, 0, c1, mx1);
int c2; long long mx2 = -1; dst[c1] = 0; dfs2(c1, 0, c2, mx2);
aux = max(aux, mx2); oki[x] = 2;
if (i) {
aux = max(aux, cs1 + dpl[i] + mx1);
aux = max(aux, cs2 + dpr[i] + mx1); }
cs1 = max(cs1, mx1 - dpl[i]);
cs2 = max(cs2, mx1 + dpl[i]); }
ans += aux; }
cout << ans << endl;
return 0; }
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |