cousins/Cousins_artur.java

  1 import java.util.Scanner;
  2 
  3 public class Cousins_artur {
  4 
  5   public static void main(String[] args) {
  6     Scanner in = new Scanner(System.in);
  7     for (int n = in.nextInt(), k = in.nextInt(); !(n == 0 && k == 0); n = in.nextInt(), k = in.nextInt()) {
  8       int nodeK = -1;
  9       int[] node = new int[n];
 10       for (int i = 0; i < n; i++) {
 11         node[i] = in.nextInt();
 12         if (node[i] == k)
 13           nodeK = i;
 14       }
 15 
 16       int[] parent = new int[n];
 17       int current = parent[0] = -1;
 18       for (int i = 1; i < n; i++) {
 19         if (node[i] != node[i - 1] + 1)
 20           current++;
 21         parent[i] = current;
 22       }
 23 
 24       int cousins = 0;
 25       if (parent[nodeK] != -1)
 26         for (int i = 1; i < n; i++)
 27           if (parent[parent[i]] == parent[parent[nodeK]] && parent[i] != parent[nodeK])
 28             cousins++;
 29       System.out.println(cousins);
 30     }
 31   }
 32 }