题目描述:
在幼儿园有n个小朋友排列为一个队伍,从左到右一个挨着一个编号为(0~n-1)。其中有一些是男生,有一些是女生,男生用'B'表示,女生用'G'表示。小朋友们都很顽皮,当一个男生挨着的是女生的时候就会发生矛盾。作为幼儿园的老师,你需要让男生挨着女生或者女生挨着男生的情况最少。你只能在原队形上进行调整,每次调整只能让相邻的两个小朋友交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整多少次可以让上述情况最少。例如:GGBBG -> GGBGB -> GGGBB这样就使之前的两处男女相邻变为一处相邻,需要调整队形2次 输入描述:输入数据包括一个长度为n且只包含G和B的字符串.n不超过50.输出描述:输出一个整数,表示最少需要的调整队伍的次数输入例子:GGBBG输出:2
我的实现:
import sys
def slice_str(str):
length = len(str)
str_arr = []
start = 0
for index in range(length - 1):
if str[index] != str[index + 1]:
sub_str = str[start : index + 1]
str_arr.append(sub_str)
start = index + 1
else:
pass
str_arr.append(str[start : ])
return str_arr
def adjust(str_arr):
move_time = 0
min_index = 0
for index, val in enumerate(str_arr):
if len(val) < len(str_arr[min_index]):
min_index = index
if min_index - 2 >= 0:
if min_index >= len(str_arr) - 2 or min_index < len(str_arr) - 2 and len(str_arr[min_index - 1]) < len(str_arr[min_index + 1]):
move_time += len(str_arr[min_index - 1]) * len(str_arr[min_index])
str_arr[min_index - 2] = str_arr[min_index - 2] + str_arr[min_index]
del str_arr[min_index]
return move_time, str_arr
if min_index + 2 < len(str_arr):
if min_index < 2 or min_index >= 2 and len(str_arr[min_index + 1 ]) < len(str_arr[min_index - 1]):
move_time += len(str_arr[min_index + 1]) * len(str_arr[min_index])
str_arr[min_index + 2] = str_arr[min_index] + str_arr[min_index + 2]
del str_arr[min_index]
return move_time, str_arr
if min_index == 1 and len(str_arr) == 3:
if len(str_arr[0]) <= len(str_arr[2]):
move_time += len(str_arr[1]) * len(str_arr[0])
str_arr[2] = str_arr[0] + str_arr[2]
del str_arr[1]
return move_time, str_arr
else:
move_time += len(str_arr[1]) * len(str_arr[2])
str_arr[0] += str_arr[2]
del str_arr[1]
return move_time, str_arr
if __name__ == "__main__":
str = sys.stdin.readline().strip("\n")
str_slice = slice_str(str)
move_time = 0
while len(str_slice) > 2:
move_t, new_str = adjust(str_slice)
move_time += move_t
new_str = "".join(new_str)
str_slice = slice_str(new_str)
print move_time, str_slice
精炼的代码:
import sys
if __name__ == '__main__':
S = sys.stdin.readline().strip()
s = [i for i in S]
loctionsB = loctionsG = icountB = icountG = 0
for i in xrange (len(s)):
if s[i] == 'B':
icountB += i - loctionsB
loctionsB += 1
else:
icountG += i - loctionsG
loctionsG += 1
print min(icountB,icountG)