hdu 3743 Frosh Week (归并排序·逆序数)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3743

Frosh Week

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2265    Accepted Submission(s): 714


Problem Description
During Frosh Week, students play various fun games to get to know each other and compete against other teams. In one such game, all the frosh on a team stand in a line, and are then asked to arrange themselves according to some criterion, such as their height, their birth date, or their student number. This rearrangement of the line must be accomplished only by successively swapping pairs of consecutive students. The team that finishes fastest wins. Thus, in order to win, you would like to minimize the number of swaps required.
 

Input
The first line of input contains one positive integer n, the number of students on the team, which will be no more than one million. The following n lines each contain one integer, the student number of each student on the team. No student number will appear more than once.
 

Output
Output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.
 

Sample Input
  
  
3 3 1 2
 

Sample Output
  
  
2
分析:求解相邻交换的次数使得所有的数字呈现单调排列。交换的次数也就是原数列的逆序数。
在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。逆序数为偶数的排列称为偶排列;逆序数为奇数的排列称为奇排列。如2431中,21,43,41,31是逆序,逆序数是4,为偶排列。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=1e6+10;
int a[maxn],b[maxn];
long long sum;
void merge(int sdex,int mdex,int edex){
    int i=sdex,j=mdex+1,k=sdex;
    while(i<=mdex&&j<=edex){
        if(a[i]<a[j]) b[k++]=a[i++];
        else b[k++]=a[j++],sum+=(mdex+1-i);
    }  //eg: 2,3  1,4 -->1,2,3,4 1越过2,3两个位置即(mdex+1-i)
    while(i!=mdex+1) b[k++]=a[i++];
    while(j!=edex+1) b[k++]=a[j++];
    for(i=sdex;i<=edex;i++) a[i]=b[i];
}
void mergesort(int sdex,int edex){
    int mdex;
    if(sdex<edex){
        mdex=(sdex+edex)/2;
        mergesort(sdex,mdex);
        mergesort(mdex+1,edex);
        merge(sdex,mdex,edex);
    }
}
int main()
{
    int n,i;
    while(cin>>n){
        sum=0;
        for(i=0;i<n;i++) scanf("%d",&a[i]);
        mergesort(0,n-1);
        printf("%lld\n",sum);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值