HDU1394Minimum Inversion Number

版权声明:欢迎大佬们前来批评指针。。(如需转载请注明出处 0_0) https://blog.csdn.net/love20165104027/article/details/82051891

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6743    Accepted Submission(s): 4112


 

Problem Description

The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.

For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:

a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)

You are asked to write a program to find the minimum inversion number out of the above sequences.

Input

The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.

Output

For each case, output the minimum inversion number on a single line.

Sample Input

10 1 3 6 9 0 8 5 7 4 2

Sample Outpu

16

看了一下别人的题解原来还有这个规律

如果求出第一种情况的逆序列,其他的可以通过递推来搞出来,一开始是t[1],t[2],t[3]....t[N]

它的逆序列个数是N个,如果把t[1]放到t[N]后面,逆序列个数会减少t[1]个,相应会增加N-(t[1]+1)个  

#include<iostream>
#include<cstdio>
#include<cstring>
#define min(x,y) x>y?y:x
using namespace std;
const int N = 5010;
int a[N];
int c[N];
int b[N];
int cnt ;

void MergeSort(int l, int r)
{
    int mid, i, j, tmp;
    if (r > l + 1)
    {
        mid = (l + r) / 2;
        MergeSort(l, mid);
        MergeSort(mid, r);
        tmp = l;
        for (i = l, j = mid; i < mid && j < r;)
        {
            if (a[i] > a[j])
            {
                c[tmp++] = a[j++];
                cnt += mid - i;
            }
            else
            {
                c[tmp++] = a[i++];
            }
        }
        if (j < r)
        {
            for (; j < r; ++j)
            {
                c[tmp++] = a[j];
            }
        }
        else
        {
            for (; i < mid; ++i)
            {
                c[tmp++]=a[i];
            }
        }
        for (i = l; i < r; ++i)
        {
            a[i] = c[i];
        }
    }
    return ;
}
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		int minn=inf;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&b[i]);
			b[i+n]=b[i];
		}
	    cnt=0;
		memcpy(a,b,n*sizeof(int));
		MergeSort(0,n);
		minn=cnt;
		for(int i=0;i<n-1;i++)
		{
			cnt=cnt-b[i]+(n-(b[i]+1));
			minn=min(minn,cnt);
		}
		printf("%d\n",minn);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/love20165104027/article/details/82051891