試題 算法訓練 Cowboys
資源限制
時間限制:2.0s 內存限制:256.0MB
問題描述
一個間不容髮的時刻:n個牛仔站立於一個環中,並且每個牛仔都用左輪手槍指着他旁邊的人!每個牛仔指着他順時針或者逆時針方向上的相鄰的人。正如很多西部片那樣,在這一刻,繩命是入刺的不可惜……對峙的場景每秒都在變化。每秒鐘牛仔們都會分析局勢,當一對相鄰的牛仔發現他們正在互指的時候,就會轉過身。一秒內每對這樣的牛仔都會轉身。所有的轉身都同時在一瞬間發生。我們用字母來表示牛仔所指的方向。“A”表示順時針方向,“B”表示逆時針方向。如此,一個僅含“A”“B”的字符串便用來表示這個由牛仔構成的環。這是由第一個指着順時針方向的牛仔做出的記錄。例如,牛仔環“ABBBABBBA”在一秒後會變成“BABBBABBA”;而牛仔環“BABBA”會變成“ABABB”。 這幅圖說明了“BABBA”怎麼變成“ABABB” 一秒過去了,現在用字符串s來表示牛仔們的排列。你的任務是求出一秒前有多少種可能的排列。如果某個排列中一個牛仔指向順時針,而在另一個排列中他指向逆時針,那麼這兩個排列就是不同的。
輸入格式
輸入數據包括一個字符串s,它只含有“A”和“B”。
輸出格式
輸出你求出來的一秒前的可能排列數。
數據規模和約定
s的長度爲3到100(包含3和100)
樣例輸入
BABBBABBA
樣例輸出
2
樣例輸入
ABABB
樣例輸出
2
樣例輸入
ABABAB
樣例輸出
4
樣例說明
測試樣例一中,可能的初始排列爲:"ABBBABBAB"和 “ABBBABBBA”。
測試樣例二中,可能的初始排列爲:“AABBB"和"BABBA”。
實現代碼
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int dp[105][2], len, pos, ans = 0;
string str;
int chm(int i) { return (i + len) % len; }
int count(int s, int e) {
memset(dp, 0, sizeof(dp));
dp[s][0] = 1, dp[s][1] = 0;
while(s != e){
s = chm(s + 1);
if (str[s] == str[chm(s - 1)]) dp[s][0] = dp[chm(s - 1)][0] + dp[chm(s - 1)][1], dp[s][1] = 0; // "AA" || "BB"
else if (str[s] == 'B') dp[s][0] = dp[chm(s - 1)][1], dp[s][1] = 0; // "AB"
else dp[s][0] = dp[chm(s - 1)][0] + dp[chm(s - 1)][1], dp[s][1] = max(1, dp[chm(s - 2)][0] + dp[chm(s - 2)][1]); // "BA"
}
return dp[e][0] + dp[e][1];
}
int last(int pos) {
int cnt = 2, s = pos + 2, e = pos - 1;
if (str[chm(e - 1)] == 'A' && str[chm(e)] == 'A') return 0;
if (str[chm(s)] == 'B' && str[chm(s + 1)] == 'B') return 0;
if (str[chm(e - 1)] == 'B' && str[chm(e)] == 'A') e -= 2, cnt += 2;
if (str[chm(s)] == 'B' && str[chm(s + 1)] == 'A') s += 2, cnt += 2;
if (cnt >= len) return 1;
else return count(chm(s), chm(e));
}
int main() {
cin >> str, len = str.length(), pos = 0;
if (str.find('B') != -1 && str.find('A') != -1) {
while (pos < len) {
if (str[pos] > str[chm(pos + 1)]) break;
pos++;
}
ans = count(chm(pos + 2), chm(pos - 1)) + last(pos);
}
cout << ans << endl;
return 0;
}