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
77
78
79
80
81
82
83
84
#include <cstdio>
#include <set>

using namespace std;

int meeting_countinuation_id[600002];
int children_count[600002];
int start_pos_for_day[600002];
int day_count;
int meetings_count;
int day;
int next_day;
int pos;
int end_pos;
int meeting_id;
int current;
int maximum;

int main() {
  // read first day
  scanf("%d %d", &day_count, &meetings_count);
  day = 0;
  pos = 0;
  end_pos = pos + meetings_count;
  start_pos_for_day[day] = pos;
  for (int i = pos; i < end_pos; i++) {
    meeting_countinuation_id[i] = -1;
    children_count[i] = 0;
  }

  // read next days
  day++;
  while (day < day_count) {
    scanf("%d", &meetings_count);
    pos = end_pos;
    end_pos = pos + meetings_count;
    start_pos_for_day[day] = pos;
    for (int i = pos; i < end_pos; i++) {
      scanf("%d", &meeting_id);
      if (meeting_id == 0) {
        meeting_countinuation_id[i] = -1;
      } else {
        meeting_countinuation_id[i] = start_pos_for_day[day - 1] + meeting_id - 1;
      }
      children_count[i] = 0;
    }
    day++;
  }
  start_pos_for_day[day] = end_pos;

  // calculate chains of events, from the end
  for (int i = end_pos - 1; i >= 0; i--) {
    // printf("CALC: %d %d\n", i, meeting_countinuation_id[i]);
    if (children_count[i] == 0) {
      children_count[i] = 1;
    }
    if (meeting_countinuation_id[i] >= 0) {
      children_count[meeting_countinuation_id[i]] = children_count[meeting_countinuation_id[i]] + children_count[i];
    }
  }

  // calculate max
  maximum = 0;
  for (day = 0; day < day_count; day++) {
    // printf("DAY: %d\n", day);
    next_day = day + 1;
    current = 0;
    for (int i = start_pos_for_day[day]; i < start_pos_for_day[next_day]; i++) {
      // printf("VAL: %d %d\n", i - start_pos_for_day[day], children_count[i]);
      current = current + children_count[i];
    }
    if (current > maximum) {
      maximum = current;
    }
    // printf("CURR: %d\n", current);
  }

  // printf("SUMAN: %d\n", start_pos_for_day[day_count]);

  // print result
  printf("%d\n", maximum);

  return 0;
}