Pagini recente » Cod sursa (job #1370499) | Cod sursa (job #2788280) | Cod sursa (job #2407384) | Cod sursa (job #2182975) | Cod sursa (job #18412)
Cod sursa(job #18412)
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.