IDENTIFICATION DIVISION.
PROGRAM-ID. 171C.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
  SELECT STDIO ASSIGN TO KEYBOARD. 
*>
DATA DIVISION.
FILE SECTION.
FD STDIO.
01 INP        PIC X(700000).
*>
WORKING-STORAGE SECTION.
01 INW        PIC X(20).
01 N          PIC 9(06) COMP.
01 Q          PIC 9(06) COMP.
01 P1         PIC 9(06) COMP.
01 P2         PIC 9(06) COMP.
01 TBL1.
   03 A       PIC 9(06) OCCURS 100000.
01 B          PIC 9(06).
01 C          PIC 9(06).
01 I          PIC 9(06) COMP.
01 IDX        PIC 9(06) COMP.
01 CNT1       PIC 9(10) COMP.
01 OUT        PIC Z(9)9.
*>
PROCEDURE DIVISION.
  ACCEPT N.
*>
  OPEN INPUT STDIO.
  READ STDIO.
  CLOSE STDIO.
*>
  MOVE ZERO TO TBL1 CNT1.
  MOVE 1    TO P1.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
    PERFORM VARYING P2 FROM P1 BY 1 UNTIL INP(P2:1) = ' '
    END-PERFORM
    MOVE INP(P1:P2 - P1) TO IDX
    ADD 1                TO A(IDX)
    ADD IDX              TO CNT1
    COMPUTE P1 = P2 + 1
  END-PERFORM.
*>
  ACCEPT Q.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > Q
    ACCEPT INW
    UNSTRING INW DELIMITED BY ' '
        INTO B C
    IF (A(B) > 0)
      COMPUTE CNT1 = CNT1 - A(B) * B + A(B) * C
      ADD  A(B) TO A(C)
      MOVE 0    TO A(B)
    END-IF
*>  
    MOVE CNT1 TO OUT
    DISPLAY FUNCTION TRIM(OUT) 
  END-PERFORM.
*>
  STOP RUN.
