File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed
Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ ```
2+ import java.io.*;
3+
4+ public class Main {
5+ private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
6+ private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
7+ private static int[] uf, size;
8+ private static int N;
9+ private static long d, bridge;
10+
11+ public static void main(String[] args) throws IOException {
12+ init();
13+
14+ bw.flush();
15+ bw.close();
16+ br.close();
17+ }
18+ private static void init() throws IOException {
19+ N = Integer.parseInt(br.readLine());
20+ d = 0;
21+ bridge = 0;
22+
23+ uf = new int[N+1];
24+ size = new int[N+1];
25+
26+ for (int i = 1; i <= N; i++) {
27+ uf[i] = i;
28+ size[i] = 1;
29+ }
30+
31+ for (int i = 0; i < N-1; i++) {
32+ int a = Integer.parseInt(br.readLine());
33+ int b = a+1;
34+
35+ int A = find(a);
36+ int B = find(b);
37+
38+ long sizeA = size[A];
39+ long sizeB = size[B];
40+
41+ d -= ((sizeA*(sizeA-1)/2) + (sizeB*(sizeB-1)/2));
42+ bridge -= ((sizeA*(sizeA*sizeA-1))/6 + (sizeB*(sizeB*sizeB-1))/6);
43+ union(A, B);
44+
45+ long newSize = sizeA + sizeB;
46+
47+ d += newSize*(newSize-1)/2;
48+ bridge += newSize*(newSize*newSize-1)/6;
49+
50+ bw.write(d + " " + bridge + "\n");
51+ }
52+ }
53+
54+ private static void union(int X, int Y) {
55+ if (X == Y) return;
56+
57+ if (size[X] < size[Y]) {
58+ uf[X] = Y;
59+ size[Y] += size[X];
60+ } else {
61+ uf[Y] = X;
62+ size[X] += size[Y];
63+ }
64+ }
65+
66+ private static int find(int x) {
67+ if (uf[x] == x) return x;
68+
69+ return uf[x] = find(uf[x]);
70+ }
71+ }
72+ ```
You can’t perform that action at this time.
0 commit comments