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

来源:互联网 发布:编程入门书籍下载 编辑:程序博客网 时间:2024/04/26 05:16

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
3312
 


 

Sample Output
2

 

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

 

#include <iostream>#include<cstdlib>#include<cstdio>#include<cstring>#define maxn 1000000+10using 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
原创粉丝点击