Help Shahhoud (18.9.30)(字串交換的最小次數)
Shahhoud is participating in the first Div.3 contest on Codeforces, the first problem was:
Given two strings A and B of equal length N (N is odd), find the minimum number of steps needed to change A into B, or print - 1 if it's impossible.
In each step, you can choose an odd integer x such that 1 ≤ x
Can you help Shahhoud solve the problem?
Input
The first line contains one integer T
Each test case consists of two lines, the first contains the string A, and the second contains the string B. (1 ≤ |A| = |B| ≤ 105) |A| = |B| is odd.
Both strings consist of lowercase English letters.
Output
For each test case, print one line containing one integer, - 1 if A
Example
Input
1 abcxdef fecxdba
Output
2
題意
給兩個一樣長的,長度為n(n%2==1)n(n%2==1)奇數的串,每一次都以(n+1)/2(n+1)/2為中心翻轉,每一次翻轉的長度是自己決定的,即每次操作都是翻轉一個x(1<=x<(n+1)/2)x(1<=x<(n+1)/2)為起點,n−x+1n−x+1為終點的串,e.g.
if(x=2),abcde==>adcbeif(x=2),abcde==>adcbe
怎樣用最少的翻轉次數使兩個串相同,輸出最少的次數,如果不能使兩個串相同輸出-11
解
翻轉策略一定從外往裡翻轉最優,複雜度O(N) 翻轉的時候不要真的在字串上操作,不要去swap,只需要一個變數time記錄已經翻了多少次,當time為偶數的時候,當前子串就是原來的樣子,time為奇數的時候當前字串是已經翻轉過一次的 e.g.
設S=abcdefg當time%2==1,i==3S沒有變,但串實際上是S′=abedcfg,我們就按照S′來做當time%2==0,i==3串實際上為S′=abcdefg設S=abcdefg當time%2==1,i==3S沒有變,但串實際上是S′=abedcfg,我們就按照S′來做當time%2==0,i==3串實際上為S′=abcdefg
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{char s1[100500],s2[100500];
int n,i,t,num,j;
scanf("%d",&t);
while(t--)
{
cin>>s1>>s2;
n=strlen(s1);
for(i=0,j=n-1;i<n;i++,j--)
{
if(s1[i]!=s2[i]&&s1[i]!=s2[j])
break;
}
if(i!=n)
printf("-1\n");
else
{
num=0;
for(i=0,j=n-1;i<n/2;i++,j--)
{
if(num%2==0)
{
if(s1[i]!=s2[i])
num++;
}
else
{
if(s1[i]!=s2[j])
{
num++;
}
}
}
printf("%d\n",num);
}
}
return 0;
}