
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2689
Sort it
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.
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
(我的代码中 此题与b[i]数组密切相关
b[i]表示
假如给你一个数组a[ ] = {2,5,3,4,1},求b[i],b[i] 表示在a[1],a[2]...a[i-1]中(即位置i的左边)小于等于a[i]的数的个数。)
好像大神们都不是我这样做的, 我有走了奇葩路线 呵呵。。
#include<iostream> using namespace std ; int sum[];
int n ; int lowbit(int x) //取x的最低位1,比如4,则返回4,如5,则返回1
{
return x&(-x);
} void update(int i, int val) //将第i个元素增加val
{
//i的祖先都要增加val
while(i <= n)
{
sum[i] += val;
i += lowbit(i); //将i的二进制未位补为得到其祖先
}
} int Sum(int i) //求前i项的和
{
int s = ;
//将前i项分段
while(i > )
{
s += sum[i];
i -= lowbit(i); //去掉i的二进制最后一个
}
return s;
} int main()
{
int i;
int a[],b[];
while(scanf("%d",&n)!=EOF)
{
int count=;
memset(b,,sizeof(b));
memset(sum,,sizeof(sum));
for(i=;i<=n;i++)
{
scanf("%d",&a[i]);
} for(i=;i<=n; i++)
{
b[i] = Sum(a[i]); //求前a[i]项的和
update(a[i],); //第a[i]个元素+1
count+=i-b[i]-;
} cout<<count<<endl; } return ;
}