-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatlarge.txt
76 lines (69 loc) · 2.66 KB
/
atlarge.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.*;
import java.util.*;
public class atlarge {
public static void main(String[] args) throws IOException {
BufferedReader f=new BufferedReader(new FileReader("atlarge.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("atlarge.out")));
StringTokenizer st = new StringTokenizer(f.readLine());
int numbarns = Integer.parseInt(st.nextToken());
int startpoint = Integer.parseInt(st.nextToken())-1;
int[][] edges = new int[numbarns-1][2];
for(int i=0; i<edges.length; i++){
st = new StringTokenizer(f.readLine());
edges[i][0]=Integer.parseInt(st.nextToken())-1;
edges[i][1]=Integer.parseInt(st.nextToken())-1;
}
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for(int i=0; i<numbarns; i++){
tree.add(new ArrayList<Integer>());
}
for(int[] i:edges){
tree.get(i[0]).add(i[1]);
tree.get(i[1]).add(i[0]);
}
HashMap<Integer,Integer> distances = new HashMap<>();
computedistances(distances,tree,startpoint,0);
ArrayList<Integer> exits = new ArrayList<>();
for(int i=0; i<tree.size(); i++){
if(tree.get(i).size()==1){
exits.add(i);
}
}
Collections.sort(exits, new Comparator<Integer>() {
@Override
public int compare(Integer integer, Integer t1) {
return Integer.compare(distances.get(integer),distances.get(t1))*-1;
}
});
int x = exits.size();
HashSet<Integer> processed = new HashSet<Integer>();
for(int i: exits){
int current =i;
processed.add(i);
for(int j=0; j<distances.get(i)/2;j++){
for(int k: tree.get(current)){
if(distances.get(k)<distances.get(current)){
current=k;
break;
}
}
if(processed.contains(current)){
x--;
break;
}else{
processed.add(current);
}
}
}
out.println(x);
out.close();
}
public static void computedistances(HashMap<Integer,Integer> map, ArrayList<ArrayList<Integer>> edges, int startpoint, int dist){
map.put(startpoint,dist);
for(int x : edges.get(startpoint)){
if(!map.containsKey(x)){
computedistances(map,edges,x,dist+1);
}
}
}
}