Sort it
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3388 Accepted Submission(s): 2455
Problem Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
Output
For each case, output the minimum times need to sort it in ascending order on a single line.
Sample Input
3 1 2 3 4 4 3 2 1
Sample Output
0 6
关于这个题,很显然是树状数组的应用,具体解释一下:我们要求整个序列转换成升序序列需要交换的最小次数,并且转换要求必须是相邻的两个数字。我们可以这么做:每次添加一个数,我们就记录当前数字中比该数小或是等于的数的个数,那么我们把每个和加起来就是要求的答案了。
如果这样不好理解,可以这样想,每加一个数,我们都要通过移动是当前的序列成为单调不递减的序列,那我们再添加一个数的时候,我们只需要找到第一个小于或的等于它的数再把它加到这个数后面不就行了?那就意味着,当前有几个数大于要添加的数,我们就需要移动多少步。
那我们直接贴出AC代码(比较简单,,就不做注释了):
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
const int maxn=1010;
int C[maxn],n;
int lowbit(int x)
{
return x&(-x);
}
void update(int i)
{
while(i<=n)
{
C[i]+=1;
i+=lowbit(i);
}
return ;
}
int query(int i)
{
int sum=0;
while(i>0)
{
sum+=C[i];
i-=lowbit(i);
}
return sum;
}
int main()
{
// freopen("s","r",stdin);
while(scanf("%d",&n)!=EOF)
{
int sum=0;
memset(C,0,sizeof(C));
for(int i=1;i<=n;i++)
{
int a;
scanf("%d",&a);
update(a);
sum+=i-query(a);
}
printf("%d\n",sum);
}
return 0;
}