Minimum Inversion Number HDU - 1394(求一个数字环的逆序对+多种解法)
題意:
給出n個數(0~n-1,每個數僅出現一次),問它長為n的循環序列中逆序對最少的數量。
多種解法:暴力+樹狀數組+分治+規律推導公式
題目:
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 Output
16
分析:
第一種解法:暴力
1.為了實現環,將數組擴到兩倍a[i+n]=a[i];
2.求出初始串的狀態,即最小逆序對;
3.由(1),直接往后遍歷,每次選取連續的n個數,即效果等同于每次把最后的元素放置最前即可實現環。
AC代碼
/**暴力*/ #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int M=1e4+10; int a[M],b[M]; int n,ans,num,cnt; int main() {while(~scanf("%d",&n)){memset(b,0,sizeof(b));for(int i=0;i<n;i++){scanf("%d",&a[i]);a[i+n]=a[i];}ans=0;for(int i=0;i<n;i++){for(int j=i+1;j<n;j++)if(a[i]>a[j])b[i]++;ans+=b[i];}for(int i=1;i<=n-1;i++){cnt=0;for(int j=i;j<i+n-1;j++){if(a[j]>a[i-1])b[j]++;cnt+=b[j];}if(ans>cnt)ans=cnt;}printf("%d\n",ans);}return 0; }第二種解法:樹狀數組求逆序數。
1.由題意:n個數(0~n-1,每個數僅出現一次),用樹狀數組來維護[0,n)的區間。
2.每次讀入一個數,將該數存入樹狀數組b[],用樹狀數組來維護[0,n)的區間和。
3.每次先求出區間[ai+1,n)的和,即為ai之前比ai大的數字的個數。
4.由前面,求出初始串的狀態,即最小逆序對
5.如序列a1,a2,a3,a4,a5,它的逆序對數量s=sum(num(ak>ai,k<i));序列變為a2,a3,a4,a5,a1,和上一個序列相比,變化分為兩步。
(1)拿走a1,逆序對減少a1( 整個序列是0~n-1且每個數字僅出現一次)個,
(2)將a1 放入序列尾部;加入序列尾部,逆序對增加n-1-a1個,這樣就可以遞推求解各序列的逆序對個數。
第三種解法:分治求逆序數
1.用分治求出初始串的狀態,每次把最后的元素放置最前即可實現環。
2.每次移動時:(與前面樹狀樹狀的后面解法一樣)
(1)所有data[i]后面比他小的元素逆序數 -1(0~k-1,k個);
(2)所有data[i]后面比他大的元素逆序數 +1(n-1-k個);
(3)逆序數改變總數是 n - 2*k - 1(k = data[i]);
枚舉不同的首元素,輸出最小的逆序數即可。
總結
以上是生活随笔為你收集整理的Minimum Inversion Number HDU - 1394(求一个数字环的逆序对+多种解法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黄苦荞的功效与作用、禁忌和食用方法
- 下一篇: Find them, Catch the