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
3
3
1
2
Sample Output
2
思路
逆序对,裸题一道吧。遇到了就水一下。线段树 或者 树状数组 或者归并排序,前两种做法需要离散化,下面贴一个线段树代码。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define ll long long
#define lson k<<1,l,m
#define rson k<<1|1,m+1,r
const int maxn = 1e6+5;
struct info{
int x,pos;
}a[maxn];
ll s[maxn*3];
bool cmp(info s1,info s2)
{
if(s1.x == s2.x){
return s1.pos < s2.pos;
}
else{
return s1.x < s2.x;
}
}
inline void update(int k,int l,int r,int ql)
{
if(l == r){
++s[k];
return ;
}
int m = (l + r) >> 1;
if(ql <= m){
update(lson,ql);
}
else{
update(rson,ql);
}
s[k] = s[k<<1] + s[k<<1|1];
}
ll query(int k,int l,int r,int ql,int qr)
{
if(qr < l || r < ql){
return 0;
}
if(ql <= l && r <= qr){
return s[k];
}
int m = (l + r) >> 1;
ll s1 = query(lson,ql,qr);
ll s2 = query(rson,ql,qr);
return s1+s2;
}
int main()
{
int n;
while(~scanf("%d",&n)){
for(int i = 0;i < n;i++){
scanf("%d",&a[i].x);
a[i].pos = i+1; //从1开始,因为线段树是从区间1开始建的不然找不到。
}
sort(a,a+n,cmp);
memset(s,0,sizeof(s));
ll sum = 0;
for(int i = 0;i < n;i++){
sum += query(1,1,n,a[i].pos,n);
update(1,1,n,a[i].pos);
}
printf("%lld\n",sum);
}
return 0;
}
愿你走出半生,归来仍是少年~