1. 程式人生 > >codeforce 804B Minimum number of steps

codeforce 804B Minimum number of steps

bst 代碼 img 添加 close perf rep spl pri

cf勁啊

原題:

We have a string of letters ‘a‘ and ‘b‘. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 10^9?+?7.

The string "ab" appears as a substring if there is a letter ‘b‘ right after the letter ‘a‘ somewhere in the string.

the initial string consisting of letters ‘a‘ and ‘b‘ only with length from 1 to 10^6.

大意:

給一個ab串,你每次能挑一個ab變成bba,問至少變多少次不能再變

串長1e6,答案膜1e9+7

b……bba?技術分享

我就是叫紫媽怎麽了?

恩核心思路就是ab變成bba後相當於把a往右挪了一下並在a前面添加一個b

這樣就好寫了從右往左掃,如果遇到b就把b的個數+1,如果遇到a就把答案加上a後面b的個數並把b的個數翻倍

因為是從右往左掃的,這樣就保證a往右挪的時候為後面的a添加的b的個數盡可能少,保證答案最小

不需要考慮一串a連在一起的情況,如果最右邊全是a,那麽不用管了對答案沒貢獻,就算左邊的a挪過去也越不過這一串a

如果中間是一串a,那麽右端點一定接了一個b,最右邊的a挪過去後次右邊又接上了b,這樣就能保證所有的a都能挪到末尾

代碼很好寫,python13行(沒壓行,寫的比較散

代碼:

技術分享
 1 mo = 1000000007
 2 a = raw_input()
 3 b, c = 0, 0
 4 i = len(a) - 1
5 while i >= 0: 6 if a[i] == a: 7 c = (c + b) % mo 8 b = (b * 2) % mo 9 else: 10 b = (b + 1) % mo 11 i = i - 1 12 13 print c
View Code

codeforce 804B Minimum number of steps