您的位置:首页 > 其它

HDU 3743 Frosh Week (归并排序)

2014-12-09 10:02 323 查看


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: