Orderly Class

本文介绍了一个有趣的编程问题:通过仅翻转字符串中的一部分连续字符来将一个字符串转换为另一个特定的目标字符串。文中提供了一段C++代码示例,展示了如何解决这一问题并计算可能的解决方案数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

Ms. Thomas is managing her class of n students.
She placed all her students in a line, and gave the i-th student from the left a card with the letter ai written on it.
She would now like to rearrange the students so that the i-th student from the left has a card with the letter bi written on it.
To do this, she will choose some consecutive group of students, and reverse their order. Students will hold on to their original cards during this process.
She’s now wondering, what is the number of valid ways to do this? (It may be impossible, in which case, the answer is zero).
With sequences abba and aabb, Ms. Thomas can choose the group a(bba). With sequences caxcab and cacxab, Ms. Thomas can choose ca(xc)ab or c(axca)b. With sequences a and z, there are clearly no solutions.

输入

The input is two lines of lowercase letters, A and B. The i-th character of A and B represent ai and bi respectively. It is guaranteed that A and B have the same positive length, and A and B are not identical. The common length is allowed to be as large as 100 000.

输出

For each test case, output a single integer, the number of ways Ms. Thomas can reverse some consecutive group of A to form the line specified by string B.

#include<bits/stdc++.h>

using namespace std;
int main()
{
int pos_1 = 0 , pos_2 = 0 ,find_1=0,find_2=0;
int ans = 0 ;
string a, b;
cin >>a;
cin >>b;
int len = a.size();
for(int i = 0 , j = len-1;i <=j ;)
{
if(a[i]==b[i])
{
i++;
}
else
{
find_1 = 1;
pos_1 = i ;
}
if(a[j]==b[j])
{
j--;
}
else
{
find_2 =1 ;
pos_2 = j;
}
if((find_1&&find_2)||i>=j)
break;
}
if(find_1==0&&find_2==0)
{
cout<<ans<<endl;
}
else
{
reverse(a.begin()+pos_1,a.begin()+pos_2+1);
if(a==b)
do{
ans++;
pos_1--;
pos_2++;
}while(a[pos_1]==a[pos_2]&&pos_1>=0&&pos_2<=len-1);
}
cout<<ans<<endl;
return 0 ;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值