fork download
  1. program mountain;
  2. Uses sysutils, Math;
  3.  
  4. const
  5. MAXN = 100005;
  6.  
  7. var
  8. ANS, N, i, j,h, maxMountainLength, lung : LongInt;
  9. P, leftLIS, rightLIS : Array[0..MAXN-1] of LongInt;
  10. rimossi : Ansistring;
  11.  
  12. begin
  13. (*assign(input, 'input.txt'); reset(input);
  14.   assign(output, 'output.txt'); rewrite(output);*)
  15. ReadLn(N);
  16. rimossi:=''; lung:=N;
  17. for i:=0 to N-1 do begin
  18. Read(P[i]);
  19. rimossi:=rimossi+IntTostr(P[i]);
  20. end;
  21. ReadLn();
  22. h:=1;
  23. while h<1001 do
  24. begin
  25. i:=2;
  26. while i<lung do
  27. begin
  28. if (rimossi[i]<rimossi[i-1]) and (rimossi[i]<rimossi[i+1]) then
  29. begin
  30. delete(rimossi,i,1);
  31. lung:=lung-1;
  32.  
  33. end;
  34. i:=i+1;
  35. end;
  36. h:=h+1;
  37. end;
  38. for i:=1 to lung do P[i-1]:=StrToInt(rimossi[i]);
  39.  
  40. ANS := 0;
  41. (*leftLIS[i] stores the length of longest increasing subsequence ending at index i*)
  42. (*rightLIS[i] stores the length of longest decreasing subsequence starting at index i*)
  43.  
  44. for i:=0 to lung-1 do begin leftLIS[i]:=1; rightLIS[i]:=1; end;
  45.  
  46. (*Calculate LIS from left to right for each position*)
  47.  
  48. for i := 1 to lung-1 do
  49. for j:= 0 to i-1 do
  50. begin
  51. if (P[i] > P[j]) then leftLIS[i] := max(leftLIS[i], leftLIS[j] + 1);
  52. end;
  53.  
  54. (* Calculate LIS from right to left (decreasing subsequence) for each position*)
  55.  
  56. for i := lung - 2 downto 0 do
  57. for j := i + 1 to lung-1 do
  58. begin
  59. if (P[i] > P[j]) then rightLIS[i] := max(rightLIS[i], rightLIS[j] + 1);
  60. end;
  61. (* Find the maximum length of mountain subsequence*)
  62. maxMountainLength := 0;
  63. for i := 0 to lung-1 do
  64. (*A valid mountain peak must have at least one element on both sides*)
  65. (*leftLIS[i] > 1 ensures there's at least one element before peak*)
  66. (*rightLIS[i] > 1 ensures there's at least one element after peak*)
  67. if (leftLIS[i] >= 1) and (rightLIS[i] >= 1) then
  68. (*Total mountain length with peak at i Subtract 1 because peak is counted in both leftLIS and rightLIS*)
  69. maxMountainLength := max(maxMountainLength, leftLIS[i] + rightLIS[i] - 1);
  70. (* Minimum removals = total elements - maximum mountain length*)
  71. ANS:= N - maxMountainLength;
  72. WriteLn(ANS);
  73. end.
  74.  
Success #stdin #stdout 0s 5288KB
stdin
8
0 1 7 5 4 6 2 3
stdout
3