Skip to content

Commit 8ecbe11

Browse files
authored
[20250318] BOJ / ? / Дерево / 권혁준
1 parent 2510770 commit 8ecbe11

File tree

1 file changed

+87
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)