hdu 2689 Sort it

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2689

题目分析:求至少交换多少次可排好序,可转换为逆序对问题。 用冒泡排序较为简单,复杂度较大~~ 也可用归并排序,复杂度O(lognn), 统计个数后复杂都不变。

/*
Sort it Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2660 Accepted Submission(s): 1910 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 */
//冒泡排序
#include <cstdio>
const int maxn = + ;
int a[maxn];
void swap(int i, int j)
{
int t;
t = a[i];
a[i] = a[j];
a[j] = t;
} int main()
{
int n;
while(~scanf("%d", &n)){
int cnt = ;
for(int i = ; i < n; i++) scanf("%d", &a[i]);
for(int i = ; i < n-; i++)
for(int j = n-; j >= i+; j--){
if(a[j] < a[j-]){
swap(j, j-);
cnt++;
}
}
printf("%d\n", cnt);
}
return ;
} //归并排序
#include <cstdio>
#include <cstring>
const int maxn = + ;
int a[maxn], t[maxn], cnt;
void merge_sort(int x, int y)
{
if(y-x > ){
int m = x + (y-x)/;
int p = x, q = m, i = x;
merge_sort(x, m);
merge_sort(m, y);
while(p < m || q < y){
if(q >= y || (p < m && a[p] <= a[q])) t[i++] = a[p++];
else {
t[i++] = a[q++];
cnt += m-p;
}
}
for(i = x; i < y; i++) a[i] = t[i];
}
} int main()
{
int n;
while(~scanf("%d", &n)){
for(int i = ; i < n; i++){
scanf("%d", &a[i]);
}
cnt = ;
merge_sort(, n);
printf("%d\n", cnt);
}
return ;
}
上一篇:【转】java读写二进制文件的解决方法


下一篇:javascript之-深入事件机制