Files
java-competitive/archive/2017.10/2017.10.27 - unsorted/С.java
2019-03-15 13:47:54 +04:00

63 lines
1.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import io.InputReader;
import io.OutputWriter;
import misc.SimpleSavingChelperSolution;
public class С extends SimpleSavingChelperSolution {
public void solve(int testNumber, InputReader in, OutputWriter out) {
wrapSolve(testNumber, in, out);
}
@Override
public void solve(int testNumber) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt() - 1;
}
boolean[] visited = new boolean[n];
List<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (visited[i]) {
continue;
}
int t = i;
int c = 0;
while (!visited[t]) {
visited[t] = true;
t = a[t];
c++;
}
b.add(c);
}
Collections.sort(b);
if (b.size() >= 2) {
int x = b.remove(b.size() - 1);
int y = b.remove(b.size() - 1);
b.add(x + y);
}
long res = 0;
for (Integer integer : b) {
res += ((long) integer) * ((long) integer);
}
out.println(res);
}
}