HDU 2689 sort it - from lanshui_Yang
2013-07-27 20:16
369 查看
[align=left]Problem Description[/align]
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
题目大意:给你一个数n ,然后有1 ~ n 的一个排列,让你找出这个排列的逆序数。
解题思路:此题可以用树状数组来解,树状数组的三个用途:1.单点更新,区间求和 2、区间更新,单点求和
3、求逆序数。求逆序数想法较简单,请看代码:
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
题目大意:给你一个数n ,然后有1 ~ n 的一个排列,让你找出这个排列的逆序数。
解题思路:此题可以用树状数组来解,树状数组的三个用途:1.单点更新,区间求和 2、区间更新,单点求和
3、求逆序数。求逆序数想法较简单,请看代码:
#include<iostream> #include<cstring> #include<string> #include<cstdio> #include<cmath> #include<algorithm> #include<queue> using namespace std ; const int MAXN = 1e5 + 7 ; int C[MAXN] ; int n ; int lowbit(int x) { return x & -x ; } int sum(int x) { int sumt = 0 ; while (x > 0) { sumt += C[x] ; x -= lowbit(x) ; } return sumt ; } void add(int x , int d) { while (x <= n) { C[x] += d ; x += lowbit(x) ; } } int main() { while (scanf("%d" , &n) != EOF) { int i ; int ans = 0 ; memset(C , 0 ,sizeof(C)) ; for(i = 1 ; i <= n ; i ++) { int a ; scanf("%d" , &a) ; add(a , 1) ; // 此处是整个程序的精华部分,请好好理解 ans += i - sum(a) ; // 统计逆序数 } printf("%d\n" , ans) ; } return 0 ; }
相关文章推荐
- HDU 2689 sort it - from lanshui_Yang
- HDU 2689 sort it - from lanshui_Yang
- HDU 2689 Sort it【树状数组】
- HDU 2689 Sort it 树状数组
- HDU 2689 HDOJ 2689 Sort it ACM 2689 IN HDU
- hdu 2689 Sort it
- HDU 2689 sort it
- hdu2689 Sort it (树状数组)
- HDU 2689 Sort it
- HDU 2689 Sort it
- hdu 2689 Sort it(线段树)
- HDU 2689 Sort it (树状数组)
- hdu 2689 Sort it
- HDU 2689 Sort it(逆序对-BIT)
- HDU - 2689 Sort it与2016蓝桥杯B 交换瓶子 排序(相邻交换与任意交换)
- HDU 2689 Sort it [树状数组]【数据结构】
- HDU2689 Sort it【树状数组】【逆序数】
- HDU 2689 Sort it 归并排序求逆序对
- hdu 2689 Sort it
- hdu 2689 Sort it 一维树状数组的应用