Under construction

Still being built. Things may change

Broken Calculator

Time limit1sMemory limit1024 MB

Summary
Insert parentheses into an expression so that a calculator with equal-priority + and * gives the intended value modulo P in every evaluation order.
Level

Medium7 of 10

Topics
Dynamic programming, String, Recursion
Solved
No attempts yet

Problem

Woojin bought a calculator for his number theory final exam. The calculator supports addition and multiplication of non-negative integers, along with grouping by parentheses, and it can compute the value of an expression that matches <expr> in the BNF below, modulo PP.

  • <expr> ::= <term> | <expr> + <term>
  • <term> ::= <factor> | <term> * <factor>
  • <factor> ::= <number> | ( <expr> )
  • <number> ::= <digit> | <number> <digit>
  • <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

A normal calculator evaluates multiplication before addition, evaluates operations inside parentheses before those outside, and evaluates operations of equal priority from left to right. This calculator is broken. It gives addition and multiplication equal priority, and it evaluates operations of equal priority in any order. For example, (2+2*2)+3 can evaluate to (4*2)+3 = 11 if the addition inside the parentheses runs first, or to (2+4)+3 = 9 if the multiplication runs first.

Ten minutes before the exam, Woojin realized the calculator is broken. As a quick fix, he will insert open parentheses ( and close parentheses ) into his expression so that the broken calculator always computes what he intended. Given the expression SS that Woojin wants to compute, write a program that inserts parentheses into SS so that the broken calculator always gives the result he intended.

Input

The first line contains the length NN of the expression and the modulus PP, separated by a space.

The second line contains the expression SS that Woojin wanted to compute.

Output

The first line prints the length MM of the converted expression TT.

The second line prints the converted expression TT.

Constraints

  • 1≤N≤501\le N\le 50
  • 2≤P≤202\le P\le 20
  • 1≤M≤1001\le M\le 100
  • SS and TT are strings made of digits and +, *, (, ).
  • SS is an expression matching <expr> in the BNF above.
  • TT is the string obtained by inserting only open and close parentheses into SS.

Examples2

  1. Example 1

    Input
    9 3
    (2+2*2)+3
    
    Expected output
    11
    (2+(2*2))+3
    
  2. Example 2

    Input
    9 2
    (2+2*2)+3
    
    Expected output
    9
    (2+2*2)+3