Skip to content

Commit 081ce8b

Browse files
authored
Merge pull request #225 from AlgorithmWithGod/khj20006
[20250311] BOJ / P5 / 등산 마니아 / 권혁준
2 parents eafe4e6 + 2029680 commit 081ce8b

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
```java
2+
3+
import java.util.*;
4+
import java.io.*;
5+
6+
7+
class Main {
8+
9+
// IO field
10+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
12+
static StringTokenizer st;
13+
14+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
15+
static int nextInt() {return Integer.parseInt(st.nextToken());}
16+
static long nextLong() {return Long.parseLong(st.nextToken());}
17+
static void bwEnd() throws Exception {bw.flush();bw.close();}
18+
19+
// Additional field
20+
21+
static int N;
22+
static List<Integer>[] V;
23+
static long[] S;
24+
static long ans = 0;
25+
26+
public static void main(String[] args) throws Exception {
27+
28+
ready();
29+
solve();
30+
31+
bwEnd();
32+
33+
}
34+
35+
static void ready() throws Exception{
36+
37+
N = Integer.parseInt(br.readLine());
38+
V = new List[N+1];
39+
S = new long[N+1];
40+
for(int i=1;i<=N;i++) V[i] = new ArrayList<>();
41+
for(int i=1;i<N;i++) {
42+
nextLine();
43+
int a = nextInt(), b = nextInt();
44+
V[a].add(b);
45+
V[b].add(a);
46+
}
47+
48+
}
49+
50+
static void solve() throws Exception{
51+
52+
dfs(1,0,0);
53+
bw.write(ans + "\n");
54+
55+
}
56+
57+
static void dfs(int n, int p, long d) {
58+
S[n] = 1;
59+
60+
for(int i:V[n]) if(i != p) {
61+
dfs(i,n,d+1);
62+
S[n] += S[i];
63+
ans += S[i] * (N-S[i]);
64+
}
65+
66+
long temp = 0;
67+
for(int i:V[n]) if(i != p) {
68+
69+
temp += S[i] * (S[n]-S[i]-1);
70+
71+
}
72+
temp = temp/2 + S[n]-1;
73+
ans += temp * d;
74+
75+
}
76+
77+
}
78+
79+
```

0 commit comments

Comments
 (0)