def parse(inFile):
[N,M] = inFile.getInts()
boxes = inFile.getInts()
toys = inFile.getInts()
boxes = [boxes[2*i:2*i+2] for i in xrange(N)]
toys = [toys[2*i:2*i+2] for i in xrange(M)]
return (boxes, toys)
def solve((boxes, toys)):
B = len(boxes)
T = len(toys)
a = [[0 for i in xrange(B+1)] for j in xrange(T+1)]
for t in xrange(T):
for b in xrange(B):
a[t+1][b+1] = max(a[t+1][b],a[t][b+1])
if (boxes[b][1] == toys[t][1]):
k = boxes[b][1]
bs = [[z,boxes[z][0]] for z in xrange(b,-1,-1) if boxes[z][1] == k]
ts = [[z,toys[z][0]] for z in xrange(t,-1,-1) if toys[z][1] == k]
for j in xrange(1,len(bs)):
bs[j][1] += bs[j-1][1]
for j in xrange(1,len(ts)):
ts[j][1] += ts[j-1][1]
a[t+1][b+1] = max(a[t+1][b+1],max([min(t0[1],b0[1])+a[t0[0]][b0[0]] for t0 in ts for b0 in bs]))
return a[-1][-1]
if __name__ == "__main__":
from GCJ import GCJ
GCJ(parse, solve, "/Users/lpebody/gcj/setup/", "c").run()
ZGVmIHBhcnNlKGluRmlsZSk6CiAgICBbTixNXSA9IGluRmlsZS5nZXRJbnRzKCkKICAgIGJveGVzID0gaW5GaWxlLmdldEludHMoKQogICAgdG95cyA9IGluRmlsZS5nZXRJbnRzKCkKICAgIGJveGVzID0gW2JveGVzWzIqaToyKmkrMl0gZm9yIGkgaW4geHJhbmdlKE4pXQogICAgdG95cyA9IFt0b3lzWzIqaToyKmkrMl0gZm9yIGkgaW4geHJhbmdlKE0pXQogICAgcmV0dXJuIChib3hlcywgdG95cykKCmRlZiBzb2x2ZSgoYm94ZXMsIHRveXMpKToKICAgIEIgPSBsZW4oYm94ZXMpCiAgICBUID0gbGVuKHRveXMpCiAgICBhID0gW1swIGZvciBpIGluIHhyYW5nZShCKzEpXSBmb3IgaiBpbiB4cmFuZ2UoVCsxKV0KICAgIGZvciB0IGluIHhyYW5nZShUKToKICAgICAgICBmb3IgYiBpbiB4cmFuZ2UoQik6CiAgICAgICAgICAgIGFbdCsxXVtiKzFdID0gbWF4KGFbdCsxXVtiXSxhW3RdW2IrMV0pCiAgICAgICAgICAgIGlmIChib3hlc1tiXVsxXSA9PSB0b3lzW3RdWzFdKToKICAgICAgICAgICAgICAgIGsgPSBib3hlc1tiXVsxXQogICAgICAgICAgICAgICAgYnMgPSBbW3osYm94ZXNbel1bMF1dIGZvciB6IGluIHhyYW5nZShiLC0xLC0xKSBpZiBib3hlc1t6XVsxXSA9PSBrXQogICAgICAgICAgICAgICAgdHMgPSBbW3osdG95c1t6XVswXV0gZm9yIHogaW4geHJhbmdlKHQsLTEsLTEpIGlmIHRveXNbel1bMV0gPT0ga10KICAgICAgICAgICAgICAgIGZvciBqIGluIHhyYW5nZSgxLGxlbihicykpOgogICAgICAgICAgICAgICAgICAgIGJzW2pdWzFdICs9IGJzW2otMV1bMV0KICAgICAgICAgICAgICAgIGZvciBqIGluIHhyYW5nZSgxLGxlbih0cykpOgogICAgICAgICAgICAgICAgICAgIHRzW2pdWzFdICs9IHRzW2otMV1bMV0KICAgICAgICAgICAgICAgIGFbdCsxXVtiKzFdID0gbWF4KGFbdCsxXVtiKzFdLG1heChbbWluKHQwWzFdLGIwWzFdKSthW3QwWzBdXVtiMFswXV0gZm9yIHQwIGluIHRzIGZvciBiMCBpbiBic10pKQogICAgcmV0dXJuIGFbLTFdWy0xXQoKaWYgX19uYW1lX18gPT0gIl9fbWFpbl9fIjoKICAgIGZyb20gR0NKIGltcG9ydCBHQ0oKICAgIEdDSihwYXJzZSwgc29sdmUsICIvVXNlcnMvbHBlYm9keS9nY2ovc2V0dXAvIiwgImMiKS5ydW4oKQoKICAgICAgICAgICAgCg==