Sort it
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2488 Accepted Submission(s): 1791
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
Author
WhereIsHeroFrom
Source
ZJFC 2009-3 Programming Contest
选择排序冒泡排序都可以做这个题,直接做就能做出来了,数太小了这个,用不着其他的东西。
在高级一点的话就用归并排序来做,也能做。
我这里是用树状数组来做的,有些大刀小用的话,也是没办法的事。
S:
#define N 1000000
#include<cstdio>
#include<cstring>
//树状数组:http://baike.baidu.com/view/1420784.htm?fr=aladdin
using namespace std;
int C[N];
int num[N];
int T;
//设节点编号为x,那么这个节点管辖的区间为2^k(其中k为x二进制末尾0的个数)个元素。因为这个区间最后一个元素必然为Ax,
//所以很明显:Cn = A(n – 2^k + 1) + ... + An
//算这个2^k有一个快捷的办法,定义一个函数如下即可
int Lowbit(int x)
{
return x & (x ^ (x - 1));
}
void add(int pos,int num)
{
while(pos <= N)
{
C[pos] += num; //存入数组C
pos += Lowbit(pos);
}
}
int Sum(int end)
{
int sum = 0;
while(end > 0)
{
sum += C[end];
end -= Lowbit(end);
}
return sum;
}
int main()
{
int s, t, i, j, T, ans;
while(~scanf("%d", &T))
{
memset(C, 0, sizeof(C)); //三步清空
memset(num, 0, sizeof(num));
ans = 0;
for(j = 0; j < T; j ++)
{
scanf("%d", &s); //输入
add(s + 1, 1); //子函传出位置与数字
ans += j - Sum(s);
}
printf("%d\n", ans);
}
return 0;
}