GYM-101808-C-Help Shahhoud

C. Help Shahhoud

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 ≤ N, and reverse the substring of length x that is centered in the middle of A. For example, performing a step with x = 3 on the string “abcde” results in “adcbe” and applying x = 5 on “abcde” results in “edcba”.

Can you help Shahhoud solve the problem?

Input

The first line contains one integer T, the number of test cases.

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 can’t be changed into B, or the minimum number of steps to change A into B.

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 ) 为起点, nx+1 n − x + 1 为终点的串,e.g.

if(x=2),abcde==>adcbe i f ( x = 2 ) , a b c d e ==> a d c b e

怎样用最少的翻转次数使两个串相同,输出最少的次数,如果不能使两个串相同输出- 1 1


翻转策略一定从外往里翻转最优,复杂度O(N)
翻转的时候不要真的在字符串上操作,不要去swap,只需要一个变量time记录已经翻了多少次,当time为偶数的时候,当前子串就是原来的样子,time为奇数的时候当前字串是已经翻转过一次的
e.g.

S=abcdefgtime%2==1,i==3SS=abedcfg,Stime%2==0,i==3S=abcdefg


string a, b;
int time;
int len;
int T;
void rev(int t) {
    time++;
}
int main()
{
    scanf("%d", &T);
    while (T--)
    {
        time = 0;
        cin >> a >> b;
        len = a.size();
        int flag = 0;
        if (a[(len) / 2] != b[(len) / 2])//中间的不一样
        {
            printf("-1\n");
            continue;
        }
        for (int i = 0; i < (len) / 2; i++) {
            if (a[i] != b[i] && a[i] != b[len - 1 - i])//翻不翻都不能一样
            {
                flag = 1;
                break;
            }
            if ((time & 1) == 0 && a[i] != b[i]) {
                if (a[i] == b[len - 1 - i] && b[i] == a[len - 1 - i])
                {
                    rev(i);
                }
            }
            else if ((time & 1) == 1 && a[i] != b[len - 1 - i]) {
                if (a[i] == b[i] && b[len - 1 - i] == a[len - 1 - i])
                {
                    rev(i);
                }
            }
        }
        if (flag == 1)printf("-1\n");
        else printf("%d\n", time);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值