#include
<
iostream
>
#include
<
string
>
#include
<
map
>
#include
<
deque
>
using
namespace
std;
struct
husband_st {
string
buy_name;
int
buy_amount;
}
*
husband_t;
husband_st mem[
1001
];
int
main() {
int
M, N, amount, count
=
0
, remain, temp_remain, first_guy, second_guy;
map
<
string
,
int
>
shop;
deque
<
int
>
line;
husband_st temp;
string
name, of;
cin
>>
M;
for
(
int
i
=
0
;i
<
M;i
++
) {
cin
>>
amount
>>
of
>>
name;
shop.insert(pair
<
string
,
int
>
(name, amount));
}
cin
>>
N;
for
(
int
i
=
0
;i
<
N;i
++
) {
cin
>>
amount
>>
of
>>
name;
temp.buy_amount
=
amount;
temp.buy_name
=
name;
mem[i]
=
temp;
line.push_back(i);
}
while
(
!
line.empty()) {
first_guy
=
line.front();
remain
=
shop[mem[first_guy].buy_name];
temp_remain
=
remain
-
mem[first_guy].buy_amount;
if
(remain
==
0
) {
//
沒貨了,老婆要打死我了 T_T
line.pop_front();
}
else
if
(temp_remain
>=
0
) {
//
有貨,可以走了 ^_^
shop[mem[first_guy].buy_name]
=
temp_remain;
line.pop_front();
}
else
{
//
貨不夠,問問老婆先
mem[first_guy].buy_amount
=
remain;
//
老婆說這個數還可以接受
line.pop_front();
if
(line.empty()) {
//
前面那人打電話問老婆去了,主角可以去買了。
count
++
;
cout
<<
count
<<
endl;
return
0
;
}
second_guy
=
line.front();
line.pop_front();
line.push_front(first_guy);
line.push_front(second_guy);
}
count
++
;
}
cout
<<
count
<<
endl;
return
0
;
}