Frosh Week(归并排序求逆序数)

H - Frosh Week

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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
 
这题的意思是第一行一个数,说明有几个数,数量不超过一百万个。然后每一行一个数,这是有顺序的,要排成递增顺序,只能相邻的两两交换,问需要交换几次
 
//vc 6这编译器真的坑了我很多次,好烦啊,长整型long long用不了,只能用 __int64 ,这题int存答案会溢出。
网上很多都是用树状数组做的,但是归并排序不是正好解决这问题的么,很简单。。。
 
 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 const int N=1000005;
 6 int num[N];
 7 int temp[N];
 8 long long ans;
 9 
10 void merge(int left,int mid,int right)
11 {
12     int i=left,j=mid+1;
13     int p=0;
14     while (i<=mid&&j<=right)
15     {
16         if (num[i]<=num[j])  temp[p++]=num[i++];
17         else
18         {
19             ans+=mid-i+1;       //前半段剩下的数的个数都多了一个逆序数
20             temp[p++]=num[j++];
21         }
22     }
23     while (i<=mid)  temp[p++]=num[i++];
24     while (j<=right)     temp[p++]=num[j++];
25     j=left;
26     for (i=0;i<p;i++)
27         num[j++]=temp[i];
28 }
29 
30 void mergesort(int left,int right)
31 {
32     int mid;
33     if (left<right)
34     {
35         mid=(left+right)/2;
36         mergesort(left,mid);    //左边还可以分的话,归并左边
37         mergesort(mid+1,right); //右边可以分的话,归并右边
38         merge(left,mid,right);  //合并两个已经并好的
39     }
40 }
41 
42 int main()
43 {
44     int n,i;
45     while (scanf("%d",&n)!=EOF)
46     {
47         ans=0;
48         for (i=0;i<n;i++)
49             scanf("%d",&num[i]);
50         mergesort(0,n-1);
51         printf("%lld\n",ans);
52     }
53     return 0;
54 }
View Code

 

 

 

转载于:https://www.cnblogs.com/haoabcd2010/p/5690997.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值