码迷,mamicode.com
首页 > 编程语言 > 详细

HDU 3743 Frosh Week (归并排序)

时间:2014-12-09 10:36:28      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:hdu   3743   逆序对   

Frosh Week

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


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
 

同样是个归并排序算逆序对的题目,根poj2299一个样,但是我一开始弄错了,原因是测试数据有好些组,所以得用while(scanf("%d",&n)!=EOF)才行。

#include<iostream>
using namespace std;
#define M 1000010
int a[M];
int aux[M];
long long int ans;
void merge(int a[],int l,int mid,int h)
{
    int i=l;
    int j=mid+1;
    for(int k=l;k<=h;++k)
        aux[k]=a[k];
    for(int k=l;k<=h;++k)
    {
        if(i>mid)a[k]=aux[j++];
        else if(j>h)a[k]=aux[i++];
        else if(aux[i]>aux[j])
        {
            a[k]=aux[j++];
            ans+=mid-i+1;
        }
        else
            a[k]=aux[i++];
    }
}
void sort(int a[],int l,int h)
{
    if(l>=h)return ;
    int mid=l+(h-l)/2;
    sort(a,l,mid);
    sort(a,mid+1,h);
    merge(a,l,mid,h);
}
int main(int argc, char *argv[])
{
   // freopen("3743.in","r",stdin);
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        memset(a,0,sizeof(a));
        memset(aux,0,sizeof(aux));
        int i=0;
        while(n--)
        {
            scanf("%d",&a[i++]);
        }
        ans=0;
        sort(a,0,i-1);
        printf("%lld\n",ans);
    }
    return 0;
}



HDU 3743 Frosh Week (归并排序)

标签:hdu   3743   逆序对   

原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41820229

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!