自己写的:超时
//在幼儿园有n个小朋友排列为一个队伍,从左到右一个挨着一个编号为(0~n - 1)。其中有一些是男生,有一些是女生,男生用'B'表示,女生用'G'表示。小朋友们都很顽皮,当一个男生挨着的是女生的时候就会发生矛盾。作为幼儿园的老师,你需要让男生挨着女生或者女生挨着男生的情况最少。你只能在原队形上进行调整,每次调整只能让相邻的两个小朋友交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整多少次可以让上述情况最少。例如:
//GGBBG->GGBGB->GGGBB
//这样就使之前的两处男女相邻变为一处相邻,需要调整队形2次
#include <cstdio>
#include<iostream>
#include <queue>
#include <vector>
#include <functional>
#include<string>
#include<cctype>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
string str;
cin >> str;
int count = 0;
int begin = 0, end = str.length()-1;
while (!(begin >= end))
{
while(str[begin] != 'B') begin++;
while (str[end] != 'G') end--;
if (begin > end) break;
count += end - begin;
begin++;
end--;
}
int count1 = 0;
begin = 0, end = str.length()-1;
while (!(begin >= end))
{
while (str[begin] != 'G') begin++;
while (str[end] != 'B') end--;
if (begin > end) break;
count1 += end - begin;
begin++;
end--;
}
cout <<(count<count1?count:count1);
return 0;
}
简短:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cin>>str;
int bCount=0,gCount=0,b=0,g=0;
for(int i=0;i<str.size();i++){
if(str[i]=='B'){
bCount+=i-b;
b++;
}
else{
gCount+=i-g;
g++;
}
}
cout<<min(bCount,gCount)<<endl;
return 0;
}