Skip to content

Commit 0a2c435

Browse files
authored
Merge pull request #829 from AlgorithmWithGod/khj20006
[20250906] BOJ / G2 / 멀지만 가까운 사이 / 권혁준
2 parents 28e4da4 + 138376b commit 0a2c435

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
class IOController {
6+
BufferedReader br;
7+
BufferedWriter bw;
8+
StringTokenizer st;
9+
10+
public IOController() {
11+
br = new BufferedReader(new InputStreamReader(System.in));
12+
bw = new BufferedWriter(new OutputStreamWriter(System.out));
13+
st = new StringTokenizer("");
14+
}
15+
16+
String nextLine() throws Exception {
17+
String line = br.readLine();
18+
st = new StringTokenizer(line);
19+
return line;
20+
}
21+
22+
String nextToken() throws Exception {
23+
while (!st.hasMoreTokens()) nextLine();
24+
return st.nextToken();
25+
}
26+
27+
int nextInt() throws Exception {
28+
return Integer.parseInt(nextToken());
29+
}
30+
31+
long nextLong() throws Exception {
32+
return Long.parseLong(nextToken());
33+
}
34+
35+
double nextDouble() throws Exception {
36+
return Double.parseDouble(nextToken());
37+
}
38+
39+
void close() throws Exception {
40+
bw.flush();
41+
bw.close();
42+
}
43+
44+
void write(String content) throws Exception {
45+
bw.write(content);
46+
}
47+
48+
}
49+
50+
public class Main {
51+
52+
static IOController io;
53+
54+
//
55+
56+
static int N;
57+
static List<int[]>[] graph;
58+
static List<Integer> list;
59+
60+
public static void main(String[] args) throws Exception {
61+
62+
io = new IOController();
63+
64+
N = io.nextInt();
65+
list = new ArrayList<>();
66+
graph = new List[N+1];
67+
for(int i=1;i<=N;i++) graph[i] = new ArrayList<>();
68+
for(int i=1;i<N;i++) {
69+
int a = io.nextInt();
70+
int b = io.nextInt();
71+
int c = io.nextInt();
72+
graph[a].add(new int[]{b,c});
73+
graph[b].add(new int[]{a,c});
74+
}
75+
76+
Queue<int[]> q = new ArrayDeque<>();
77+
boolean[] vis = new boolean[N+1];
78+
q.offer(new int[]{1,0});
79+
vis[1] = true;
80+
while(!q.isEmpty()) {
81+
int[] cur = q.poll();
82+
int n = cur[0], v = cur[1];
83+
list.add(v);
84+
for(int[] e:graph[n]) if(!vis[e[0]]) {
85+
vis[e[0]] = true;
86+
q.offer(new int[]{e[0],v^e[1]});
87+
}
88+
}
89+
Collections.sort(list);
90+
91+
long ans = 0, cnt = 1;
92+
int prev = list.get(0);
93+
for(int i=1;i<N;i++) {
94+
int v = list.get(i);
95+
if(v != prev) {
96+
ans += cnt*(cnt-1)/2;
97+
cnt = 0;
98+
}
99+
cnt++;
100+
prev = v;
101+
}
102+
ans += cnt*(cnt-1)/2;
103+
104+
io.write(ans + "\n");
105+
106+
io.close();
107+
108+
}
109+
110+
}
111+
```

0 commit comments

Comments
 (0)