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

归并排序求逆序数

时间:2014-11-19 15:53:49      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   io   ar   os   sp   for   strong   

A - Frosh Week
Time Limit:8000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu
Appoint description: 

Description

bubuko.com,布布扣
 

Problem E: Frosh Week

bubuko.com,布布扣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 Specification

Input contains several test cases. For each test case, 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.

Sample Input

3
3
1
2

Output Specification

For each test case, output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.

Output for Sample Input

2

Ond?ej Lhoták
#include <stdio.h>  
  
#define N  1000001  
  
typedef long long LL;  
  
int n;  
int num[N], tmp[N];  
  
int input()  
{  
    if (scanf("%d", &n) != 1) return 0;  
      
    int i;  
    for (i = 0; i < n; i++) {  
        scanf("%d", &num[i]);  
    }  
    return 1;  
}  
  
LL mergesort(int l, int r, int a[])  
{  
    if (l >= r) return 0;  
      
    int m = (l + r) >> 1;  
    LL s1 = mergesort(l, m, a);  
    LL s2 = mergesort(m + 1, r, a);  
    LL sum = s1 + s2;  
      
    int p = l, q = m + 1;  
    int k = l;  
      
    while (p <= m || q <= r) {  
        if (p > m || (q <= r && a[p] > a[q])) {  
            tmp[k++] = a[q++];  
            sum += m + 1 - p;  
        } else {  
            tmp[k++] = a[p++];  
        }  
    }  
      
    int i;  
    for (i = l; i <= r; i++) {  
        a[i] = tmp[i];  
    }  
      
    return sum;  
}  
  
void solve()  
{  
    LL ans = mergesort(0, n - 1, num);  
    printf("%lld\n", ans);  
}  
  
int main()  
{  
    #ifndef ONLINE_JUDGE  
        freopen("d:\\OJ\\uva_in.txt", "r", stdin);  
    #endif  
      
    while (input()) {  
        solve();  
    }  
    return 0;  
}  

  

归并排序求逆序数

标签:des   blog   http   io   ar   os   sp   for   strong   

原文地址:http://www.cnblogs.com/a972290869/p/4108313.html

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