KEI Day (c group) (2)

Topic (2) (closest to God's people)

 Cracked Runewords, small FF opened the road leading to the ground. When he went to the bottom, there is a stone found in front of the door, carved with a pattern of some kind of ancient human activity on the door. The above Shimen says "temple of God" with the ancient text. FF guess there should be little royal heritage inside. But the question now is how to open the door ......           
       after careful study, he found that the pattern on the door probably say: ancient people think that only the wise man is the most accessible of the gods. The most intelligent people often selected out through a ritual. Probably it refers to the ceremony, is about to retire wise to write down a bunch of digital disorder for his candidate, and allow them to carrying out an operation that swaps two elements adjacent sequences. And with the least number of exchanges so that people do not fall into the original sequence that is the next sequence wise.
       Small FF n digits has found the same door. So he thought to open the door of the secret is to find a way to become this sequence does not decrease the minimum number required sequence. However, the small FF would not ...... and had to find you, and promise you three things can be done after the seven ......

Entry

Conduct a first integer n, it denotes the sequence length of
the second line n integers, each representing a sequence of elements.

Export

An integer ans, i.e., a minimum number of operations.

Sample input

4
2 8 0 3

Sample Output

3 
Sample Description: The 
starting sequence is 2803, the target sequence is 0238, can be performed to obtain target sequence three operations: 
1. Swap (8 0): 2 0 3. 8 
2. Swap (2, 0) : 0 2. 8. 3 
3. Swap (. 8,. 3): 0 2. 8. 3

Data range limit

For 30% of the data 1 <= n <= 10 ^ 4.
100% of the data. 1 <= n-<= ^. 5 * 10. 5;
-maxlongint <= A [I] <= maxlongint.

 Thinking

This is a standard sequence of inverse problem, you can use merge sort.

Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
long long int a[500001],r[500001],ans=0,n;
void gsort(int s,int t)
{
    if(s==t)
    return ;
    int mid=(s+t)/2;
    gsort(s,mid);
    gsort(mid+1,t);
    int i=s,j=mid+1,k=s;
    while(i<=mid&&j<=t)
    {
        if(a[i]<=a[j])
        {
            r[k]=a[i];
            i++;
            k++;
        }
        else
        {
            r[k]=a[j];
            j++;
            k++;
            ans=ans+mid-i+1;
        }
    }
    while(i<=mid)
    {
        r[k]=a[i];
        i++;
        k++;
    }
    while(j<=t)
    {
        r[k]=a[j];
        j++;
        k++;
    }
    for(int i=s;i<=t;i++)
    a[i]=r[i];
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    cin>>a[i];
    gsort(1,n);
    cout<<ans<<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/abcdhh/p/11299660.html