描述
给出运算符算式,保持运算符顺序不变的情况下,可进行若干次如下操作:交换相邻的两个数,表达式值不变,那么就可以交换这两个数
那么可进行任意次操作,使得算式的数字序列字典序最小,输出结果(字典序定义为若a<b则a字典序小于b)
用 python 写的
def worker(e, num_total):
"""
"-" and "/" can not exchange
:param e:
:param num_total:
:return:
"""
parts = e.split()
nums = []
symbols = []
for idx, one in enumerate(parts):
if idx % 2 == 0: # num
nums.append(int(one))
else: # symbol
symbols.append(one)
# Gather continues "+" and "*"
mul_part_idx = []
add_part_idx = []
symbols_len = len(symbols)
idx = 0
while idx < symbols_len:
if symbols[idx] == '+':
tmp_part = []
while idx < symbols_len and symbols[idx] == '+':
tmp_part.append(idx)
idx += 1
add_part_idx.append(tmp_part)
if idx >= symbols_len:
break
if symbols[idx] == '*':
tmp_part = []
while idx < symbols_len and symbols[idx] == '*':
tmp_part.append(idx)
idx += 1
mul_part_idx.append(tmp_part)
if idx >= symbols_len:
break
if symbols[idx] in ["-", "/"]:
idx += 1
pass
# Get num for symbol part idx
for mul_plst in mul_part_idx:
pick_idx_lst = mul_plst
pick_idx_lst.append(mul_plst[-1] + 1)
pick_num_lst = [nums[i] for i in pick_idx_lst]
new_num_lst = sorted(pick_num_lst)
nums_front_part = nums[:pick_idx_lst[0]]
nums_back_part = nums[pick_idx_lst[-1] + 1:]
nums = nums_front_part + new_num_lst + nums_back_part
for add_plst in add_part_idx:
if len(add_plst) <= 1:
continue
pick_idx_lst = add_plst
fin_pick_idx_lst = []
for i, pick_idx in enumerate(pick_idx_lst):
if i == 0 and pick_idx != 0:
continue
fin_pick_idx_lst.append(pick_idx)
if pick_idx + 1 < symbols_len:
if symbols[pick_idx + 1] == "-":
fin_pick_idx_lst.append(pick_idx+1)
pick_num_lst = [nums[i] for i in fin_pick_idx_lst]
new_num_lst = sorted(pick_num_lst)
nums_front_part = nums[:fin_pick_idx_lst[0]]
nums_back_part = nums[fin_pick_idx_lst[-1] + 1:]
nums = nums_front_part + new_num_lst + nums_back_part
# Rebuild equation
new_e = []
sym_cnt = 0
num_cnt = 0
for idx in range(2 * num_total - 1):
if idx % 2 == 0: # num
new_e.append(str(nums[num_cnt]))
num_cnt += 1
else: # symbol
new_e.append(symbols[sym_cnt])
sym_cnt += 1
new_e = " ".join(new_e)
return new_e
N = int(input())
equation = input()
# N = 6
# equation = '3 + 2 + 1 + -4 * -5 + 1'
print(worker(equation, N))