AB Substrings (思维)题解

Problem Statement

Snuke has N strings. The i-th string is si

Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

  • 1≤N≤104
  • 2≤|si|≤10
  • si consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s1

sN

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4

题意

给n个字符串,你可以将其任意进行连接,求连接后的字符串中AB的数量

思路

一道思维题,连接后的字符串中AB的数量包括两部分
1.连接前每一段字符串中AB的数量
2.连接产生的AB的数量
1.好算,遍历一遍就行了,我们来讲讲2.
首先一段字符串和另一段字符串连接后如果能产生AB那么第一段字符串的末尾一定是A,第二段字符串的第一个一定是B,还有一种特殊情况就是这段字符串的第一个是B并且最后一个是A,当且仅当两组字符串满足以上三种情况中不重复的两种时,才能产生AB,我们就记录给出所有字符串中的三种情况的数量,分别用变量A,B,AB表示,连接字符串时先让所有的AB连接,那么产生了AB-1个AB,连接完第一个一定是B,最后一个一定是A,我们再接上这两个部位,又产生了2个AB,同时A和B变量也要减1,最后连接只有A和只有B的字符串,就是取他们两者的最小值,最后连接在一起就行了,还是要手动模拟一下比较好

AC代码

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#define ios ios::sync_with_stdio(false)
using namespace std;
typedef long long ll;
const int maxn=1e4+100;
string a[maxn];
int main()
{
	ios;
	int n,A=0,B=0,AB=0; cin>>n;
	ll sum=0;
	for(int i=0;i<n;i++){
		cin>>a[i];
		int len=a[i].size()-1;
		for(int j=1;j<=len;j++){
			if(a[i][j]=='B'&&a[i][j-1]=='A') sum++;
		}
		if(a[i][0]=='B'&&a[i][len]=='A'){
			AB++; continue;
		}
		if(a[i][0]=='B'){
			B++; continue;
		}
		if(a[i][len]=='A'){
			A++; continue;
		}
	}
	ll ans=0;
	if(AB>0){		当既有A又有B时
		if(A>0||B>0){
			A-=1; B-=1;
			ans+=2;AB-=1;			
		}
		else AB-=1;
	}
	ans+=min(A,B)+AB+sum;
	cout<<ans<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我的Doraemon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值