问题 F: Orderly Class
时间限制: 1 Sec 内存限制: 128 MB提交: 100 解决: 34
[ 提交][ 状态][ 讨论版][命题人: admin]
题目描述
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.
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.
样例输入
abba
aabb
样例输出
1
题目大意:对给定的一个字符串看是否可以通过一次交换,变成下面所要求的字符串,问有几种方法可以通过一次交换完成目标字符串
解题思想:如果可以通过一次交换实现目标字符串,则a,b两个字符串的交换部分是完全对称的,然后再检测交换部分的两侧有多少对相等的字符个数
例: caxcab 变成cacxab, 可以通过交换(cx),也可以交换(acxa)两种方法来实现。(对应位置相同可视为一次交换的选择。)
c语言给出代码:
#include<stdio.h>
#include<string.h>
char a[100100]={'\0'},b[100100]={'\0'};
int main()
{ int i,j,n,l,r,countt;
scanf("%s",a);
getchar();
scanf("%s",b);
n=strlen(a);
for(i=0;i<n;i++){
if(a[i]!=b[i]){
l=i;
break;
}
}
for(i=n-1;i>=0;i--){
if(a[i]!=b[i]){
r=i;
break;
}
} //两次循环确定l和r,来找到最小的交换体
for(i=l,j=r;i<=r;j--,i++){
if(a[i]!=b[j]){
printf("0\n");
return 0;
}
} //判断交换体中是否满足完全对称
l--;
r++;
countt=1;
while(l>=0&&r<n&&a[l]==a[r]){
l--;
r++;
countt++;
} //判断交换体两侧有多少对相等的字符个数
printf("%d\n",countt);
return 0;
}