Cod sursa(job #18412)

Utilizator raduzerRadu Zernoveanu raduzer Data 18 februarie 2007 12:02:35
Problema Tricouri Scor 0
Compilator fpc Status done
Runda preONI 2007, Runda 2, Clasa a 9-a si gimnaziu Marime 1.35 kb
var a:array[1..300000]of longint;
    n,k,i,j,s,m,p,q,z:longint;



procedure Sort(l, r: Integer);
var
  i, j, x, y: integer;
begin
  i := l; j := r; x := a[(l+r) DIV 2];
  repeat
    while a[i] < x do i := i + 1;
    while x < a[j] do j := j - 1;
    if i <= j then
    begin
      y := a[i]; a[i] := a[j]; a[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sort(l, j);
  if i < r then Sort(i, r);
end;


begin
     assign(input,'tricouri.in');
     reset(input);
     assign(output,'tricouri.out');
     rewrite(output);
     readln(n,k);
     for i:=1 to n do read(a[i]);
     sort(1,n);
     for i:=1 to k do
     begin
          s:=0;
          readln(m,p);
          for j:=n downto 1 do
          begin
               s:=s+a[j];
               if (s mod p=0)and(n-j+1>=m) then break;
          end;
          if s mod p<>0 then
          begin
               writeln(-1);
               continue;
          end;
          q:=n-j+1;
          z:=q;
          j:=n+1;
          while (q>m)and(j>z) do
          begin
               j:=j-1;
               if a[j] mod p=0 then
               begin
                    q:=q-1;
                    s:=s-a[j];
               end;
          end;
          if q>m then writeln(-1)
          else writeln(s);
     end;
close(output);
end.