[2019] National training day2-s secret message

\(Description\)

\ (Smart \) received a secret message from extraterrestrial. Mail a \ (n \) capital English letters, Unfortunately \ (Smart \) after receipt of the mail accidentally disrupted the original alphabetical order. But smart \ (Smart \) to remember the complete contents of the original message, and now he can choose to e-mail each time after the upset in two adjacent letters exchanged, the exchange asked the least number of times will be able to disrupt mail recovery into the original message.

\(Input\)

The first row \ (1 \) integer \ (n-\) represents a message length.

The second line of length \ (n-\) contains only uppercase letters represented by a string of messages after the upset.

The third row of length \ (n-\) contains only the capital letters represent the original message string.

In order to ensure the mail after the upset can be restored to the original message, all test data meet the same number of occurrences of any of the two capital letters in the mail.

\(Output\)

Outputting a minimum integer number of exchanges.

\(Sample Input 1\)

4
ABCD
DBCA

\(Sample Output 1\)

5

\(Hint\)

【data range】

\ (40% \) Data \ (: n≤30 \) ;

Further \ (20% \) Data \ (: n = 5000; \ )

\ (100% \) Data \ (: n≤1000000 \) .

\(Solution\)

Obviously the reverse of ......
the mail disruption in capital letters eleven numbers, and then map them to the original message.
Here we encounter the same initials appear multiple times, then we will consider uppercase letters first appeared earlier in the map

Like Sample

\ (ABCD \)
\ (DBCA \)

\ (1234 \)
after mapping is
\ (4231 \)
and then find the answer is \ (4231 \) the number of reverse sequence
\ ((4,2) \) \ (( 4,3) \) \ ((4,1) \) \ ((2,1) \) \ ((3,1) \)

The number can be used to reverse seeking Fenwick tree \ (or \) merge sort ......
here is the merge sort

#include<bits/stdc++.h>
#define Re register int
using namespace std;
vector<long long> W[27];
long long N,a[1000050],b[1000050],Now[27];
long long Ans;
char S_Mess[1000050],S_Last[1000050];
inline void merge_sort(int l,int r){
    if(r-l>0){
        int mid=(l+r)>>1;
        int Wh=l;
        int p=l,q=mid+1;
        merge_sort(l,mid);
        merge_sort(mid+1,r);
        while(p<=mid || q<=r){
            if(q>r || (p<=mid && a[p]<=a[q])) b[Wh++]=a[p++];
            else{
                b[Wh++]=a[q++];
                Ans+=mid-p+1;
            }
        }
        for(Re i=l; i<=r; i++) a[i]=b[i];
    }
}
int main(){
    scanf("%d",&N);
    scanf("%s",S_Mess+1);
        scanf("%s",S_Last+1);
    for (Re i=1; i<=N; ++i) W[S_Last[i]-'A'+1].push_back(i);
    for (Re i=1; i<=N; ++i) a[i]=W[S_Mess[i]-'A'+1][Now[S_Mess[i]-'A'+1]++];
    merge_sort(1,N);
    printf("%lld",Ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/to-the-end/p/11617800.html