Alpha and Beta
Time Limit:1000MS Memory Limit:65536K
Total Submit:491 Accepted:62
Description
Alpha and Beta are best friends and make company with each other all the time.
There is a time when a game called “make pairs” gains much popularity. Alpha and Beta are very fond of it and like to invite you to play with them.
Given a string, which is simply composed of either A or B, they want to know how many AB pairs can Alpha and Beta find in that string. Can you help them?
A pair is legal if and only if A appears at first, and whether B is near to A is not required. In other words, B makes pair with A which is nearest before B, and they both can be used only once.
Input
There are a series of strings. The length of each string is less than 1000.
Output
For each case, if there is none legal pair that they can find, print -1. Otherwise, print the number of them.
Please note the output format.
Sample Input
BA
AABB
BAB
Sample Output
Case #1: -1
Case #2: 2
Case #3: 1
题意:给定一个只含有A和B的字符串,问可以配对多少组A...B,若某A和某B配对以后则不可以再和别的B配对。
解法:因为要求A在B的前面,所以我们只需从头遍历一遍,找几个变量N记录A出现的次数,每出现一次A就让N自增一次,当出现B的时候,就判断一下前面有没有多余的A剩下,如果有那么消耗一个A,让N自减一次,然后答案ANS+1,如果没有A剩下了那么很遗憾,这个B就不能配对了。
AC代码:
//************************************************************************//
//*Author : Handsome How *//
//************************************************************************//
//#pragma comment(linker, "/STA CK:1024000000,1024000000")
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
//----------------------------------------------------------
int a;
int main()
{char s[2000];int kase = 0;while(scanf("%s",s)!=EOF){a=0;int ans = 0;int len = strlen(s);for(int i=0;i<len;i++){if(s[i]=='A')a++;else if(a>0){ans++;a--;}}if(ans==0)ans=-1;printf("Case #%d: ",++kase);printf("%d\n",ans);}return 0;
}