fork download
  1. { NOTE: it is recommended to use this even if you don't understand the following code. }
  2.  
  3. { constraints }
  4. const
  5. MAXN = 100000;
  6.  
  7. { input data }
  8. var
  9. N, i, temp : longint;
  10. A : array[0..MAXN-1] of longint;
  11. T : array[1..MAXN] of longint;
  12. ft : array[1..MAXN] of longint;
  13. best : array[1..MAXN] of longint;
  14.  
  15. procedure update(i: longint; v: longint);
  16. begin
  17. i := N-i+1;
  18. while (i <= N) do
  19. begin
  20. if v > ft[i] then
  21. ft[i] := v;
  22. i := i + (i and (-i));
  23. end;
  24. end;
  25.  
  26. function get(i:longint) : longint;
  27. var res: longint;
  28. begin
  29. res := 0;
  30. i := N-i+1;
  31. while (i > 0) do
  32. begin
  33. if res < ft[i] then
  34. res := ft[i];
  35. i := i - (i and (-i));
  36. end;
  37. get := res;
  38. end;
  39.  
  40.  
  41. begin
  42. {
  43.   uncomment the following lines if you want to read/write from files
  44.   assign(input, 'input.txt'); reset(input);
  45.   assign(output, 'output.txt'); rewrite(output);
  46. }
  47.  
  48. readln(N);
  49. for i:=0 to N-1 do
  50. read(A[i]);
  51. readln();
  52. for i:=1 to N do
  53. read(T[i]);
  54. readln();
  55.  
  56. {
  57.   WARNING! T is indexed from 1!
  58.   In particular T[i] is the preferred number of i.
  59.   }
  60.  
  61. for i:=1 to N do
  62. begin
  63. best[i] := 0;
  64. ft[i] := 0;
  65. end;
  66.  
  67. i := N-1;
  68. while i >= 0 do
  69. begin
  70. if best[T[A[i]]]+1 > best[A[i]] then
  71. best[A[i]] := best[T[A[i]]]+1;
  72. temp := get(A[i]+1)+1; writeln(temp,' ', A[i],' ',i);
  73. if temp > best[A[i]] then
  74. best[A[i]] := temp;
  75. update(A[i], best[A[i]]);
  76. i := i-1;
  77. end;
  78.  
  79.  
  80.  
  81. { insert your code here }
  82.  
  83. writeln(get(1)); { print result }
  84. end.
  85.  
Success #stdin #stdout 0s 5320KB
stdin
6
1 2 3 1 2 3
6 5 1 3 2 1
stdout
1 3 5
2 2 4
3 1 3
1 3 2
5 2 1
6 1 0
6