#P8269. [USACO22OPEN] Visits S
[USACO22OPEN] Visits S
Problem Description
Bessie has () cow friends (numbered ), and each of them owns her own farm. For each , friend wants to visit friend ().
Given a permutation of , the visits happen as follows.
For each from to :
- If friend has already left her farm, then friend stays at her farm.
- Otherwise, friend leaves her farm to visit friend 's farm. This visit produces happy moos times ().
Among all possible permutations , compute the maximum total number of moos that can be obtained after all visits finish.
Input Format
The first line contains .
For each , line contains two space-separated integers and .
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 , then:
- Friend visits friend 's farm, producing moos.
- Friend sees that friend has already left her farm, so nothing happens.
- Friend visits friend 's farm, producing another moos.
- Friend sees that friend has already left her farm, so nothing happens.
So in total we get moos.
On the other hand, if , then:
- Friend visits friend 's farm, producing moos.
- Friend visits friend 's farm, producing moos.
- Friend visits friend 's farm, producing moos.
- Friend sees that friend has already left her farm, so nothing happens.
So in total we get moos. It can be proven that this is the maximum possible number of moos after all visits finish among all possible permutations .
Translated by ChatGPT 5