Sort it
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3418 Accepted Submission(s): 2478
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
Author
WhereIsHeroFrom
Source
ZJFC 2009-3 Programming Contest
题意,用冒泡排序的方法把n个数排成按升序排列需要几步。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
const int N = 1001;
int n;
int num[N];
int c[N];
struct node{
int x;
int id;
}q[N] ;
bool cmp(node a,node b){
return a.x < b.x;
}
int lowbit(int x){
return x&(-x);
}
int getsum(int x){
int s = 0;
while(x>0){
s += c[x];
x -= lowbit(x);
}
return s;
}
void add(int x,int y){
while(x<=n){
c[x] += y;
x += lowbit(x);
}
}
int main()
{
while(scanf("%d",&n)!=EOF){
memset(c,0,sizeof(c));
memset(num,0,sizeof(num));
for(int i=1;i<=n;i++){
scanf("%d",&q[i].x);
q[i].id = i;
}
sort(q+1,q+1+n,cmp);
for(int i=1;i<=n;i++){
num[q[i].id] = i;
}
int sum = 0;
for(int i=1;i<=n;i++){
add(num[i],1);
sum += getsum(n) - getsum(num[i]);
}
printf("%d\n",sum);
}
return 0;
}