IDENTIFICATION DIVISION.
PROGRAM-ID. A-BEGINNER.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 INP     PIC X(501).
01 IN-DATA.
   03 DT-X1 PIC X(10).
   03 DT-X2 PIC X(10).
01 IN-LEN.
   03 DT-L1 PIC 9(2).
   03 DT-L2 PIC 9(2).
01 IN-N     PIC 9(6).
01 IN-S     PIC X(10).
01 IN-TABLE.
   03 I-STR PIC X(10) OCCURS 20000.
   03 I-CNT PIC 9(6)  OCCURS 20000.
   03 I-NXT PIC 9(6)  OCCURS 20000.
01 T-CNT    PIC 9(6).
01 T-STA    PIC 9(6).
01 POS      PIC 9(6).
01 POS-PRE  PIC 9(6).
01 I        PIC 9(6).
01 J        PIC 9(6).
01 CNT-MAX  PIC 9(6).
 
PROCEDURE DIVISION.
MAIN-001.
  ACCEPT INP.
  UNSTRING INP DELIMITED BY ALL ' '
      INTO DT-X1 COUNT IN DT-L1.
  MOVE DT-X1(1:DT-L1) TO IN-N.
 
  ACCEPT I-STR(1).
  MOVE 1 TO I-CNT(1).
  MOVE 0 TO I-NXT(1).
  MOVE 1 TO CNT-MAX.
  MOVE 1 TO T-STA.
  MOVE 1 TO T-CNT.

  PERFORM VARYING I FROM 2 BY 1 UNTIL I > IN-N
    ACCEPT IN-S
    MOVE T-STA TO  POS POS-PRE
    PERFORM VARYING J FROM 1 BY 1 
              UNTIL (J > T-CNT) OR
                    (IN-S <= I-STR(POS)) 
      MOVE POS        TO POS-PRE
      MOVE I-NXT(POS) TO POS
    END-PERFORM

    IF (J > T-CNT)
      ADD 1 TO T-CNT
      MOVE IN-S    TO I-STR(T-CNT)
      MOVE 1       TO I-CNT(T-CNT)
      MOVE 0       TO I-NXT(T-CNT)
      MOVE T-CNT   TO I-NXT(POS-PRE)
    ELSE
      IF (IN-S = I-STR(POS))
        ADD 1        TO I-CNT(POS) 
        IF (I-CNT(POS) > CNT-MAX)
          MOVE I-CNT(POS) TO CNT-MAX
        END-IF
      ELSE
        ADD 1 TO T-CNT
        MOVE IN-S    TO I-STR(T-CNT)
        MOVE 1       TO I-CNT(T-CNT)
        MOVE POS     TO I-NXT(T-CNT)
        IF (POS = T-STA)
          MOVE T-CNT TO T-STA
        ELSE
          MOVE T-CNT TO I-NXT(POS-PRE)
        END-IF
      END-IF
    END-IF
  END-PERFORM.
      
  MOVE T-STA TO POS. 
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > T-CNT
    IF (I-CNT(POS) = CNT-MAX)
      DISPLAY I-STR(POS)
    END-IF

    MOVE I-NXT(POS) TO POS
  END-PERFORM.

MAIN-EXIT.
  STOP RUN.
