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
Solution
This problem can be solved using Merge Sort.Here is the C implementation of this problem.
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
Solution
This problem can be solved using Merge Sort.Here is the C implementation of this problem.
#include <stdio.h> #define sz 1000000 #define inf 1000000000 long a[sz+2],L[sz+2],R[sz+2]; long long cnt; void merge(long p,long q,long r){ long i,j,k,ind1,ind2; for(i = p,ind1 = 1;i <= q;i++){ L[ind1++] = a[i]; } L[ind1] = inf; for(i = q+1,ind2 = 1;i <= r;i++){ R[ind2++] = a[i]; } R[ind2] = inf; i = j = 1; for(k = p;k <= r;k++){ if(L[i] > R[j]){ cnt += ind1 - i; a[k] = R[j]; j++; } else{ a[k] = L[i]; i++; } } } void mergeSort(long p,long r){ if(p < r){ long q = (p+r)/2; mergeSort(p,q); mergeSort(q+1,r); merge(p,q,r); } } int main(){ long i,n; while(scanf("%ld",&n) == 1){ for(i = 1;i <= n; i++){ scanf("%ld",&a[i]); } cnt = 0; mergeSort(1,n); printf("%lld\n",cnt); } return 0; }
No comments:
Post a Comment