IDENTIFICATION DIVISION.
PROGRAM-ID. 097C.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 S          PIC X(5000).
01 K          PIC 9(1) COMP.
01 I          PIC 9(4) COMP.
01 J          PIC 9(4) COMP.
01 JW         PIC 9(4) COMP.
01 TBL.
   03 DIC     PIC X(5) OCCURS 25000 DEPENDING ON S-N.
01 S-N        PIC 9(5) COMP.
01 IX         PIC 9(5) COMP.
01 LEN        PIC 9(4) COMP. 
01 OUT        PIC X(5).
*>
PROCEDURE DIVISION.
  ACCEPT S.
  ACCEPT K.
  UNSTRING S DELIMITED BY ' '
      INTO S COUNT LEN.
*>
  if (LEN < 5)
    COMPUTE S-N = LEN * (LEN + 1) / 2
  ELSE
    COMPUTE S-N = (LEN - 4) * 5 + 10
  END-IF.
*>
  MOVE 0 TO IX.  
  MOVE SPACE TO TBL.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > LEN
    PERFORM VARYING J FROM 1 BY 1 UNTIL J > 5 OR I + J - 1 > LEN
      ADD 1 TO IX
      MOVE S(I:J) TO DIC(IX)
    END-PERFORM  
  END-PERFORM.
*>
  SORT DIC ASCENDING KEY DIC.
*>
  MOVE 1 TO I J.
  PERFORM UNTIL I >= K
    MOVE J TO JW
    PERFORM VARYING J FROM JW BY 1 UNTIL DIC(J) NOT = DIC(JW)
    END-PERFORM
    ADD 1 TO I
  END-PERFORM.
  MOVE DIC(J) TO OUT.
*>
  DISPLAY FUNCTION TRIM(OUT).
  STOP RUN.
