暑假集训(2)第六弹 ----- Frosh Week(UVA11858)

H - Frosh Week

Crawling in process... Crawling failed 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
 
问题分析:显然这是一道求逆序数的题目,可用归并排序求解。
 1 #include "cstdio"
 2 
 3 int num[1000005];
 4 int T[1000005];
 5 __int64 sum;
 6 void mset(int n)
 7 {
 8   for (int i=1;i<=n;i++)
 9     scanf ("%d",&num[i]);
10 }
11 void px(int x,int y)
12 {
13    if (y-x > 1)
14    {
15        int m = x + (y-x)/2;
16        int p = x,q = m,i = x;
17        px(x,m);
18        px(m,y);
19        while (p < m || q < y)
20        {
21            if (q >= y || (p < m && num[p] <= num[q]))
22                  T[i++] = num[p++];
23            else
24            {
25                T[i++] = num[q++];
26                sum += m-p;
27            }
28        }
29       for (i=x;i<y;i++)
30          num[i] = T[i];
31    }
32 }
33 int main()
34 {
35     int n;
36     while (~scanf ("%d",&n))
37     {
38            sum=0;
39            mset(n);
40            px(1,n+1);
41             for (int i=1;i<=n;i++)
42         printf ("%d ",num[i]);
43            printf ("%I64d
",sum);
44     }
45 
46     return 0;
47 }
View Code
原文地址:https://www.cnblogs.com/huas-zlw/p/5697030.html