cousins/cousins_vanb.java
1
2 import java.io.*;
3 import java.util.*;
4 import java.awt.geom.*;
5
6
7
8
9
10
11 public class cousins_vanb
12 {
13 public Scanner sc;
14 public PrintStream ps;
15
16
17
18
19
20
21
22 public class Node
23 {
24 public int kids, grandkids;
25 public Node parent;
26
27
28
29
30
31 public Node( Node parent )
32 {
33
34 kids = grandkids = 0;
35
36
37 this.parent = parent;
38 }
39 }
40
41
42
43
44
45 public void doit() throws Exception
46 {
47 sc = new Scanner( new File( "cousins.judge" ) );
48 ps = new PrintStream( new FileOutputStream( "cousins.solution" ) );
49
50
51 HashMap<Integer,Node> nodes = new HashMap<Integer,Node>();
52 Node tree[] = new Node[1000];
53
54 for(;;)
55 {
56 int n = sc.nextInt();
57 int k = sc.nextInt();
58 if( n==0 ) break;
59
60
61 Arrays.fill( tree, null );
62
63
64 int root = sc.nextInt();
65 tree[0] = new Node(null);
66 nodes.clear();
67 nodes.put( root, tree[0] );
68
69
70 int parent = -1;
71 int last = -1;
72 for( int i=1; i<n; i++ )
73 {
74
75
76 int nodenum = sc.nextInt();
77 if( nodenum>last+1 ) ++parent;
78
79
80 tree[i] = new Node( tree[parent] );
81 nodes.put( nodenum, tree[i] );
82
83
84 tree[parent].kids++;
85
86
87 if( tree[parent].parent!=null ) tree[parent].parent.grandkids++;
88
89
90 last = nodenum;
91 }
92
93
94 Node node = nodes.get( k );
95
96
97 if( node==null )
98 {
99 System.err.println( "PANIC!! Node " + k + " isn't in the tree! " + nodes );
100 }
101 else if( node.parent==null || node.parent.parent==null )
102 {
103
104
105 ps.println(0);
106 }
107 else
108 {
109
110 ps.println( node.parent.parent.grandkids - node.parent.kids );
111 }
112 }
113 }
114
115
116
117
118 public static void main( String[] args ) throws Exception
119 {
120 new cousins_vanb().doit();
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 }
149 }