git reimport
This commit is contained in:
62
archive/2017.10/2017.10.27 - unsorted/С.java
Normal file
62
archive/2017.10/2017.10.27 - unsorted/С.java
Normal file
@@ -0,0 +1,62 @@
|
||||
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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user