码迷,mamicode.com
首页 > 其他好文 > 详细

H - Frosh Week

时间:2016-07-21 12:26:22      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

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用不了,我很少想到存不了这个问题,每次都要用double解决,这题int存答案会溢出。
网上很多都是用树状数组做的,但是归并排序不是正好解决这问题的么,很简单。。。
 
技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int N=1000005;
 5 int num[N];
 6 int temp[N];
 7 long long ans;
 8 
 9 void merge(int left,int mid,int right)
10 {
11     int i=left,j=mid+1;
12     int p=0;
13     while (i<=mid&&j<=right)
14     {
15         if (num[i]<=num[j])  temp[p++]=num[i++];
16         else
17         {
18             ans+=mid-i+1;       //就是num[j]到num[i]要经过几次调换
19             temp[p++]=num[j++];
20         }
21     }
22     while (i<=mid)  temp[p++]=num[i++];
23     while (j<=right)     temp[p++]=num[j++]; 
24     j=left;
25     for (i=0;i<p;i++)
26         num[j++]=temp[i];
27 }
28 
29 void mergesort(int left,int right)
30 {
31     int mid;
32     if (left<right)
33     {
34         mid=(left+right)/2;
35         mergesort(left,mid);    //左边还可以分的话,归并左边
36         mergesort(mid+1,right); //右边可以分的话,归并右边
37         merge(left,mid,right);  //合并两个已经并好的
38     }
39 }
40 
41 int main()
42 {
43     int n,i;
44     while (scanf("%d",&n)!=EOF)
45     {
46         ans=0;
47         for (i=0;i<n;i++) 
48             scanf("%d",&num[i]);
49         mergesort(0,n-1);
50         printf("%lld\n",ans);
51     }
52     return 0;
53 }
View Code

 

H - Frosh Week

标签:

原文地址:http://www.cnblogs.com/haoabcd2010/p/5690997.html

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