Alpha and Beta

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值