BNU29375:Two Strings

Eyelids loves playing strings very much. One day he has two strings S and W, both consisting of lowercase letters and having length of m. For each string he has two operations to change the letters:
1. Swap two adjacent letters and pay no cost;
2. Change one letter x to y and pay |x-y|.
He wonders the minimal cost to change the string S to W only with the two operations.
 

Input

The first line contains a single integer T, indicating the number of test cases.
The first line of each test case contains an integer m (1<=m<=100000), followed by two strings S and W separated by a single space, which only contains lowercase letters.

Output

For each test case, output the case number first, then the minimal cost.

Sample Input

2
3
abc abc
5
bcabc bdcbd

Sample Output

Case 1: 0
Case 2: 4
 
由于交换是无消耗的,所以可以排序后再计算
 
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

char s1[100005],s2[100005];
int ans;

int abs(int a)
{
    if(a<0)
        return -a;
    return a;
}

int main()
{
    int t,m,cas = 1,i;
    scanf("%d",&t);
    while(t--)
    {
        ans = 0;
        scanf("%d%s%s",&m,s1,s2);
        sort(s1,s1+m);
        sort(s2,s2+m);
        for(i = 0; i<m; i++)
            if(s1[i]!=s2[i])
                ans+=abs(s1[i]-s2[i]);
        printf("Case %d: %d\n",cas++,ans);

    }
    return 0;
}

你可能感兴趣的:(水,BNU)