| def is_valid_roman(s):
|
| values = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
|
| prev_value = float('inf')
|
|
|
| # Проверка повторений
|
| repeats = {'M': 0, 'D': 0, 'C': 0, 'L': 0, 'X': 0, 'V': 0, 'I': 0}
|
| for c in s:
|
| repeats[c] += 1
|
| if repeats[c] > 3: # Более 3 повторений любого символа
|
| return False
|
| if c in 'DLV' and repeats[c] > 1: # D, L, V не могут повторяться
|
| return False
|
|
|
| # Проверка порядка и допустимых вычитаний
|
| for i in range(len(s)):
|
| curr_value = values[s[i]]
|
| if i > 0:
|
| prev_char = s[i-1]
|
| if values[prev_char] < curr_value:
|
| # Проверка допустимых вычитаний
|
| if prev_char + s[i] not in ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']:
|
| return False
|
| prev_value = curr_value
|
| return True
|
|
|
| def roman_to_decimal(s):
|
| values = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
|
| total = 0
|
| prev_value = 0
|
|
|
| for c in reversed(s):
|
| curr_value = values[c]
|
| if curr_value >= prev_value:
|
| total += curr_value
|
| else:
|
| total -= curr_value
|
| prev_value = curr_value
|
| return total
|
|
|
| def find_valid_roman(s):
|
| from itertools import permutations
|
| chars = list(s)
|
| max_valid = 0
|
|
|
| for perm in permutations(chars):
|
| roman = ''.join(perm)
|
| if is_valid_roman(roman):
|
| value = roman_to_decimal(roman)
|
| max_valid = max(max_valid, value)
|
|
|
| return max_valid
|
|
|
| # Пример использования
|
| input_string = "MDCLXVI"
|
| result = find_valid_roman(input_string)
|
| print(result)
|