IDENTIFICATION DIVISION.
PROGRAM-ID. 162D.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 N          PIC  9(4).
01 S          PIC  X(4000).
01 I1         PIC  9(4) COMP.
01 I2         PIC  9(4) COMP.
01 I3         PIC  9(4) COMP.
01 IR         PIC  9(4) COMP.
01 IG         PIC  9(4) COMP.
01 IB         PIC  9(4) COMP.
01 IW         PIC  9(4) COMP.
01 KS         PIC  9(18).
01 S1         PIC  9(4) COMP.
01 M1         PIC S9(4) COMP.
01 M2         PIC S9(4) COMP.
01 M3         PIC S9(4) COMP.
01 MP         PIC  9(4) COMP.
01 AMR        PIC  9(1) COMP.
01 OUT        PIC  Z(17)9.
01 TBL-R.
   03 RN      PIC  9(4) COMP OCCURS 4001.
   03 RN2     PIC  9(1)      OCCURS 4001.
01 TBL-G.
   03 GN      PIC  9(4) COMP OCCURS 4001.
   03 GN2     PIC  9(1)      OCCURS 4001.
01 TBL-B.
   03 BN      PIC  9(4) COMP OCCURS 4001.
   03 BN2     PIC  9(1)     OCCURS 4001.
01 TBL-W.
   03 WN      PIC  9(4) COMP OCCURS 4001.
   03 WN2     PIC  9(1)      OCCURS 4001. 
*>
PROCEDURE DIVISION.
  ACCEPT N.
  ACCEPT S.
*>
  MOVE ZERO TO TBL-R TBL-G TBL-B.
  PERFORM VARYING I1 FROM 1 BY 1 UNTIL I1 > 4001
    MOVE 0 TO RN(I1) GN(I1) BN(I1)
  END-PERFORM.
*>
  MOVE 0 TO IR IG IB.
  PERFORM VARYING I1 FROM 1 BY 1 UNTIL I1 > N
    EVALUATE S(I1:1)
      WHEN 'R'
        ADD   1 TO IR
        MOVE I1 TO RN(IR)
        MOVE  1 TO RN2(I1)
      WHEN 'G'
        ADD   1 TO IG
        MOVE I1 TO GN(IG)
        MOVE  1 TO GN2(I1)
      WHEN 'B'
        ADD   1 TO IB
        MOVE I1 TO BN(IB)
        MOVE  1 TO BN2(I1)
    END-EVALUATE  
  END-PERFORM.
*>
  EVALUATE TRUE
    WHEN IR >= IG AND IR >= IB
      MOVE TBL-R TO TBL-W
      MOVE IR    TO IW
      MOVE TBL-B TO TBL-R
      MOVE IB    TO IR
      MOVE TBL-W TO TBL-B
      MOVE IW    TO IB
    WHEN IG >= IR AND IG >= IB
      MOVE TBL-G TO TBL-W
      MOVE IG    TO IW
      MOVE TBL-B TO TBL-G
      MOVE IB    TO IG
      MOVE TBL-W TO TBL-B
      MOVE IW    TO IB
  END-EVALUATE.      
*>
  MOVE 0 TO KS.
 if (IR > 0) AND (IG > 0) AND (IB > 0)
  PERFORM VARYING I1 FROM 1 BY 1 UNTIL I1 > IR
    PERFORM VARYING I2 FROM 1 BY 1 UNTIL I2 > IG
      COMPUTE S1 = RN(I1) - GN(I2)
      COMPUTE MP = RN(I1) + GN(I2)
      DIVIDE MP BY 2 GIVING M2 REMAINDER AMR
      IF (AMR = 1)
        MOVE 4001 TO M2
      END-IF
*>
      IF (RN(I1) < GN(I2))
        COMPUTE M1 = RN(I1) - S1
        IF (M1 < 1)
          MOVE 4001 TO M1
        END-IF
        COMPUTE M3 = GN(I2) + S1
        IF (M3 > N)
          MOVE 4001 TO M3
        END-IF
      ELSE
        COMPUTE M1 = GN(I2) - S1
        IF (M1 < 1)
          MOVE 4001 TO M1
        END-IF
        COMPUTE M3 = RN(I1) + S1
        IF (M3 > N)
          MOVE 4001 TO M3
        END-IF
      END-IF
*>
      COMPUTE KS = KS + IB - BN2(M1) - BN2(M2) - BN2(M3)
    END-PERFORM
  END-PERFORM
 END-IF.
*>
  MOVE KS TO OUT.
  DISPLAY FUNCTION TRIM(OUT).
  STOP RUN.
