试题 算法训练 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;
}