fork(1) download
  1. import std.algorithm;
  2. import std.conv;
  3. import std.range;
  4. import std.stdio;
  5. import std.string;
  6.  
  7. void main ()
  8. {
  9. int n;
  10. while (readf (" %s", &n) > 0)
  11. {
  12. auto p = new int [n];
  13. auto c = new char [n];
  14. auto a = new int [] [n];
  15. foreach (i; 1..n)
  16. {
  17. readf (" %s %s", &p[i], &c[i]);
  18. p[i] -= 1;
  19. a[p[i]] ~= i;
  20. }
  21.  
  22. auto vis = new bool [n];
  23. auto dist = new int [n];
  24. auto next = new int [n];
  25. auto term = new int [n];
  26. term = n.iota.array;
  27. next[] = -1;
  28.  
  29. bool less (int u, int v)
  30. {
  31. bool cur = false;
  32. do
  33. {
  34. if (c[u] != c[v])
  35. {
  36. return c[u] > c[v];
  37. }
  38. cur = (u < v);
  39. u = next[u];
  40. v = next[v];
  41. }
  42. while (u != -1);
  43. return cur;
  44. }
  45.  
  46. void recur (int v)
  47. {
  48. if (vis[v])
  49. {
  50. return;
  51. }
  52. vis[v] = true;
  53.  
  54. foreach (u; a[v])
  55. {
  56. recur (u);
  57. int cand = dist[u] + 1;
  58. if (dist[v] < cand || (dist[v] == cand &&
  59. less (u, next[v])))
  60. {
  61. dist[v] = cand;
  62. next[v] = u;
  63. term[v] = term[u];
  64. }
  65. }
  66. debug {writeln (v, ": ", dist[v], " ",
  67. next[v], " ", term[v]);}
  68. }
  69.  
  70. foreach (i; 0..n)
  71. {
  72. if (!vis[i])
  73. {
  74. recur (i);
  75. }
  76. writeln (dist[i] > 0 ? term[i] + 1 : 0);
  77. }
  78. }
  79. }
  80.  
Success #stdin #stdout 0s 4164KB
stdin
6
1 b
2 c
1 b
4 d
5 e

6
1 b
2 d
1 b
4 c
5 e

1

5
1 b
2 c
1 b
4 d

5
1 b
2 d
1 b
4 c

5
1 b
1 b
3 c
3 a
stdout
6
3
0
6
6
0
6
3
0
6
6
0
0
5
3
0
5
0
3
3
0
5
0
4
0
4
0
0