标签:
Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2772 Accepted Submission(s): 923
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
Sample Output
题目大意:求逆序数对数;
解题思路:归并排序;
#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
int a[1000005];
int b[1000005]; //辅助数组
long long cnt;
void Merge(int a[],int p,int q,int r, int b[]){
int s = p, t = q + 1, k = p;
while(s <= q && t <= r){
if(a[s] <= a[t]){
b[k ++] = a[s ++];
}else{
b[k ++] = a[t ++];
cnt += (q - s + 1); // 在原序列a[s...q] > a[t],故有逆序数对 (q-s+1) 个
}
}
if(s == q + 1)
for(;t <= r;t ++) b[k ++] = a[t];
else
for(;s <= q;s ++) b[k ++] = a[s];
for(int i = p;i < k;i ++)
a[i] = b[i];
}
void BottomUpSort(int a[],int first,int last,int b[]){
if(first < last){
int mid = (first + last) / 2;
BottomUpSort(a, first, mid, b);
BottomUpSort(a, mid + 1, last, b);
Merge(a, first, mid, last, b);
}
}
int main(){
int n;
while(scanf("%d",&n) != EOF){
cnt = 0;
for(int i = 1;i <= n;i ++)
scanf("%d",&a[i]);
BottomUpSort(a,1,n, b);
printf("%I64d\n",cnt);
}
return 0;
}
Frosh Week(HDU_3743)归并排序+逆序数对
标签:
原文地址:http://blog.csdn.net/keeping111/article/details/51335748