HDU 3743 Frosh Week 【归并排序模板题】

Frosh Week

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


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

 

嗯,题目大意就是说,首先是数据个数,之后是数据,要求的就是将这些数据从小到大排序需要的最小的交换次数

 

#include <iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#define maxn 1000000+10
using namespace std;
long long n,cnt,a[maxn];
void Merge(long long *a,long long left,long long mid,long long right,long long *p)
{
    long long n=mid,m=right;
    long long i=left,j=mid+1;
    long long k=0;
    while(i<=n&&j<=m)
    {
        if(a[i]<=a[j])
            p[k++]=a[i++];
        else
        {
            p[k++]=a[j++];
            cnt+=n-i+1;//因为a[i]到a[mid]位有序的,一旦a[i]>a[j]则从i到mid的所有数都大于a[j]因为题目从小到大排序所以这些数都需要交换到a[j]的后面
        }
    }
    while(i<=n)
    {
        p[k++]=a[i++];
    }
    while(j<=m)
        p[k++]=a[j++];
    for(int i=0;i<k;++i)
        a[left+i]=p[i];
}
void mergesort(long long *a,long long left,long long right,long long *p)
{
    if(left<right)
    {
        int mid=(left+right)/2;
        mergesort(a,left,mid,p);
        mergesort(a,mid+1,right,p);
        Merge(a,left,mid,right,p);
    }
}
int main()
{
    while(cin>>n)
    {
        cnt=0;
        for(int i=0;i<n;++i)
            cin>>a[i];
        long long *p=(long long *)malloc(sizeof(long long )*n);
        mergesort(a,0,n-1,p);
        cout<<cnt<<endl;
        free(p);
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值