program foo;
  const
    maxk = 1000;
  type

   TE =  record
       salis: string [2];
       data: string [10];
       kiekis: integer;
     end;

   Tlent = array [0 .. maxk] of TE;

  var
    n, k, i: integer;
    f1, f2: text;
    lent: Tlent;
    kk, suma, ssuma, dar1, dar2, parduos: integer;
    temp: char;
    err: word;
    kodas, sk, ss: string;
    viso, pard: longint;

procedure quicksort(var a: Tlent; Lo,Hi: integer);

procedure sort(l,r: integer);
var
  i,j: integer;
  y: Te;
  x: string;
begin
  i:=l; j:=r; x:=a[(l+r) DIV 2].data;
  repeat
    while a[i].data<x do i:=i+1;
    while x<a[j].data 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 {quicksort};
  sort(Lo,Hi);
end;


function minimum (d1, d2: integer): integer;
begin
  if d1 < d2
    then minimum := d1
    else minimum := d2;
end;

begin
  assign (f1, 'sand.in');
  assign (f2, 'sand.out');
  reset (f1);
  rewrite (f2);
  readln (f1, n, k);
  readln (f1, kodas);
  viso := 0;
  for i := 1 to k do
    begin
      readln (f1, ss);
      lent [i].salis := copy (ss, 1, 2);
      lent [i].data := copy (ss, 4, 10);
      delete (ss, 1, 14);
      val (ss, lent [i].kiekis, err);
      viso := viso + lent [i].kiekis;
    end;
  quicksort (lent, 1, k);

{   writeln (viso); }
  pard := viso - n;

  suma := 0;
  ssuma := 0;
  kk := 1;
  while (kk <= k) and (suma < pard) do begin
    dar1 := pard - suma; { kiek dar reikia parduot }
    dar2 := lent [kk].kiekis; { kiek galima parduot }
    parduos := minimum (dar1, dar2);
    suma := suma + parduos;
    if lent [kk].salis = kodas then ssuma := ssuma + parduos;
    inc (kk);
  end;
  writeln (f2, ssuma);
  close (f1);
  close (f2);
end.