#P8269. [USACO22OPEN] Visits S

    ID: 9349 远端评测题 2000ms 256MiB 尝试: 0 已通过: 0 难度: 6 上传者: 标签>USACO2022拓扑排序连通块强连通分量基环树

[USACO22OPEN] Visits S

Problem Description

Bessie has NN (2N1052\le N\le 10^5) cow friends (numbered 1N1\cdots N), and each of them owns her own farm. For each 1iN1\le i\le N, friend ii wants to visit friend aia_i (aiia_i\neq i).

Given a permutation (p1,p2,,pN)(p_1,p_2,\ldots, p_N) of 1N1\ldots N, the visits happen as follows.

For each ii from 11 to NN:

  • If friend apia_{p_i} has already left her farm, then friend pip_i stays at her farm.
  • Otherwise, friend pip_i leaves her farm to visit friend apia_{p_i}'s farm. This visit produces happy moos vpiv_{p_i} times (0vpi1090\le v_{p_i}\le 10^9).

Among all possible permutations pp, compute the maximum total number of moos that can be obtained after all visits finish.

Input Format

The first line contains NN.

For each 1iN1\le i\le N, line i+1i+1 contains two space-separated integers aia_i and viv_i.

Output Format

Output one integer, the required answer.

Note that the integers in this problem may require 64-bit integer types (for example, "long long" in C/C++).

4
2 10
3 20
4 30
1 40
90

Hint

[Sample Explanation]

If p=(1,4,3,2)p=(1,4,3,2), then:

  • Friend 11 visits friend 22's farm, producing 1010 moos.
  • Friend 44 sees that friend 11 has already left her farm, so nothing happens.
  • Friend 33 visits friend 44's farm, producing another 3030 moos.
  • Friend 22 sees that friend 33 has already left her farm, so nothing happens.

So in total we get 10+30=4010+30=40 moos.

On the other hand, if p=(2,3,4,1)p=(2,3,4,1), then:

  • Friend 22 visits friend 33's farm, producing 2020 moos.
  • Friend 33 visits friend 44's farm, producing 3030 moos.
  • Friend 44 visits friend 11's farm, producing 4040 moos.
  • Friend 11 sees that friend 22 has already left her farm, so nothing happens.

So in total we get 20+30+40=9020+30+40=90 moos. It can be proven that this is the maximum possible number of moos after all visits finish among all possible permutations pp.

Translated by ChatGPT 5