39A - C++ Calculations - CodeForces Solution


expression parsing greedy *2000

Please click on ads to support us..

Python Code:

from typing import List, Tuple, Optional
from collections import deque, Counter
from queue import PriorityQueue
import math
from functools import lru_cache
import random
import copy
import sys
sys.setrecursionlimit(9999)


MOD = 10**9 + 7



init_a = int(input())
s = input()

n = len(s)
i = 0

ss = ""
while i < n:
    if i+2 <= n-1 and (s[i:i+3] == 'a++' or s[i:i+3] == '++a'):
        ss += "X" if s[i:i+3] == 'a++' else 'Y'
        i += 3
    else:
        ss += s[i]
        i += 1

if ss[0] != '-':
    ss = '+' + ss

arr = []
f = []
n = len(ss)
i = 0
while i < n:
    j = i
    while j+1 < n and (ss[j+1] != 'X' and ss[j+1] != 'Y'):
        j += 1

    if ss[j] == '*':
        v = int(ss[i: j])
        arr.append((v, ss[j+1]))
    else:
        if ss[i] == '-':
            arr.append((-1, ss[j+1]))
        else:
            arr.append((1, ss[j+1]))

    i = j+2


arr.sort()

a = init_a
tot = 0
for v, ch in arr:
    if ch == 'Y':
        a += 1

    tot += a * v

    if ch == 'X':
        a += 1


print(tot)


Comments

Submit
0 Comments
More Questions

67B - Restoration of the Permutation
1734A - Select Three Sticks
1734B - Bright Nice Brilliant
357B - Flag Day
937A - Olympiad
1075A - The King's Race
1734C - Removing Smallest Multiples
1004C - Sonya and Robots
922A - Cloning Toys
817A - Treasure Hunt
1136B - Nastya Is Playing Computer Games
1388A - Captain Flint and Crew Recruitment
592B - The Monster and the Squirrel
1081A - Definite Game
721C - Journey
1400A - String Similarity
1734E - Rectangular Congruence
1312D - Count the Arrays
424C - Magic Formulas
1730C - Minimum Notation
1730B - Meeting on the Line
1730A - Planets
302B - Eugeny and Play List
1730D - Prefixes and Suffixes
1515C - Phoenix and Towers
998A - Balloons
1734F - Zeros and Ones
1144B - Parity Alternated Deletions
92B - Binary Number
1144C - Two Shuffled Sequences