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

猜你喜欢

转载自blog.csdn.net/AGNING/article/details/105778667
ab