fork download
  1. program pastryshop;
  2.  
  3. const
  4. MAXN = 100000;
  5.  
  6. type elenco=array [0..MAXN-1] of Longint;
  7.  
  8. var
  9. D, K, N, i : LongInt;
  10. P : elenco;
  11.  
  12.  
  13.  
  14. Procedure scambia (var a,b: longint);
  15. var x:longint;
  16. begin
  17. x:=a;
  18. a:=b;
  19. b:=x;
  20. end;
  21. Procedure ordinamento (estremoi,estremos: Longint; var v : elenco; ordinato:boolean);
  22. var inf, sup, medio:Longint;
  23. pivot :longint;
  24. begin
  25. inf:=estremoi;
  26. sup:=estremos;
  27. medio:= (estremoi+estremos) div 2;
  28. pivot:=v[medio];
  29. repeat
  30. if (ordinato) then
  31. begin
  32. while (v[inf]<pivot) do inf:=inf+1;
  33. while (v[sup]>pivot) do sup:=sup-1;
  34. end;
  35. if inf<=sup then
  36. begin
  37. scambia(v[inf],v[sup]);
  38. inf:=inf+1;
  39. sup:=sup-1;
  40. end;
  41. until inf>sup;
  42. if (estremoi<sup) then ordinamento(estremoi,sup,v,ordinato);
  43. if (inf<estremos) then ordinamento(inf,estremos,v,ordinato);
  44. end;
  45.  
  46.  
  47. begin
  48. {
  49.   uncomment the two following lines if you want to read/write from files
  50.   assign(input, 'input.txt'); reset(input);
  51.   assign(output, 'output.txt'); rewrite(output);
  52. }
  53.  
  54. ReadLn(N, K);
  55.  
  56. for i:=0 to N-1 do
  57. Read(P[i]);
  58. ReadLn();
  59.  
  60. ordinamento (0,N-1,P,true);
  61.  
  62. if K>=N-1 then D:=0
  63. else
  64. begin
  65. D:=P[N-K-1]-P[0];
  66. for i:=1 to K do
  67. if P[i+(N-K)-1]-P[i]<D then D:=P[i+(N-K)-1]-P[i];
  68. end;
  69.  
  70. WriteLn(D);
  71.  
  72. end.
  73.  
Success #stdin #stdout 0s 548KB
stdin
5 2
2 5 8 12 20
stdout
6