题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3743
Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1798 Accepted Submission(s): 599
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
Source
思路:
(1)n个数乱序排列,现在可以移动任意一对相邻的数使得其位置发生变化,问最少移动多少次可以使得n个数从小到大排列~
比如: 5 4 3 1 2 五个数,通过观察可以发现 若一个数左边有k个大于他本身的数,那么至少得移动k次;这不就是逆序数的问题吗~
所以可以利用树状数组求出来~
(2)另外一点就是: 题目并没有说这n个数是1~n之间的数,所以得离散化为1到n之间,也就是一一映射;
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
const int N=1e6+100;
typedef long long ll;
using namespace std;
ll c[N];
int n,b[N];
struct node
{
int id,num;
}a[N];
bool cmp(node a,node b)
{
return a.num<b.num;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int d)
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}
int getsum(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].num);
a[i].id=i;
}
sort(a+1,a+1+n,cmp);
memset(c,0,sizeof(c));
memset(b,0,sizeof(b));
for(int i=1;i<=n;i++)
{
b[a[i].id]=i;
}
ll cnt=0;
for(int i=1;i<=n;i++)
{
cnt+=i-1-getsum(b[i]);
update(b[i],1);
}
printf("%I64d\n",cnt);
}
return 0;
}