# encoding = utf-8
# 开发者:xxx
# 开发时间: 0:21
# "Stay hungry,stay foolish."
def huiwen(n, s): # 判断能不能组成回文数
temp_D = set()
temp_S = set()
if n % 2 == 0:
for i in range(26):
if s.count(chr(ord('a') + i)) % 2 != 0: # 如果某个字符不是偶数个
print('Impossible')
return False
else:
return True
else:
for j in range(26):
word = chr(ord('a') + j)
# 统计了字符串 s 中特定字符(ASCII 值在 'a' 之后 j 个字符)出现的次数。
if s.count(word) % 2 == 0:
temp_D.add(word) # 把个数是奇数个的字符放进temp
else:
temp_S.add(word)
if len(temp_S) >= 2:
print('Impossible')
return False
else:
return True
# 贪心策略:
# 对于偶数的字符串,我们从第一个开始遍历,再倒序遍历出同样的,这个倒序遍历出来的序号,就是该移动的步数。我们把这个步数加到总步数之后,用pop弹出这个值。进行第二轮遍历。
# 遍历用n/2做大循环,用另一个序列做倒序序列,倒序序列更新后,原来的序列也要更新。
def step(n, s, s1, res):
for i in range(n // 2):
if s[i:].count(s[i]) != 1: # 次数是否不等于 1
temp = s1[:n - i].index(s[i]) # 是要移动的步数
s1.pop(temp)
res += temp
s = s1[::-1]
else:
res += n // 2 - i
s[i] = None
s1 = s[::-1]
return res
n = int(input())
s = list(input())
s1 = s[::-1]
res = 0
if huiwen(n, s):
print(step(n, s, s1, res))
Python 蓝桥杯 基础练习 完美的代价 贪心算法(正确代码)
最新推荐文章于 2025-12-01 13:49:36 发布
966





