Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 999 Accepted Submission(s): 307
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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
const int M = 1000005;
int a[M] , c[M] , val[M];
int lowbit( int x )
{
return x&(-x);
}
int find( int x , int l , int r )
{
int mid;
while( l < r )
{
mid = (l+r) / 2;
if( val[mid] == x )
return mid;
else if( x >= val[mid] )
l = mid + 1;
else
r = mid - 1;
}
return l;
}
int query( int x )
{
int ret = 0;
while( x > 0 )
{
ret += c[x];
x -= lowbit(x);
}
return ret;
}
void update( int x )
{
while( x < M )
{
c[x]++;
x += lowbit(x);
}
}
int main( )
{
int n;
while( ~scanf("%d",&n) )
{
memset( a , 0 , sizeof(a) );
memset( c , 0 , sizeof(c) );
memset( val , 0 , sizeof(val) );
for( int i=1 ; i<=n ; i++ )
{
scanf("%d",&a[i]);
val[i] = a[i];
}
sort( val+1 , val+1+n );
__int64 ans = 0;
for( int i=1 ; i<=n ; i++ )
{
int x = find( a[i] , 1 , n );
int cnt = 0;
cnt += query( x-1 );
ans += i - cnt - 1;
update( x );
}
printf("%I64d\n",ans);
}
return 0;
}