HDU 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
題解:倒著求,每次統計 a[i]後邊有多少個比它小,同時更新a[i]出現的次數。(樹狀陣列維護的是字首和......牢記)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1005;
int n;
int a[maxn], c[maxn];
int lowbit(int x) {
return x & -x;
}
int get_sum(int x){
int sum = 0;
while(x){
sum += c[x];
x -= lowbit(x);
}
return sum;
}
void add(int x, int val) {
while(x <= n){
c[x] += val;
x += lowbit(x);
}
}
int main()
{
while(~scanf("%d", &n)){
memset(c, 0, sizeof c);
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
int ans = 0;
for(int i = n; i >= 1; i--){//倒序統計
ans += get_sum(a[i] - 1);//查詢a[i]後邊有多少個數比它小
add(a[i], 1);//a[i]出現的次數+1
}
printf("%d\n", ans);
}
return 0;
}
相關文章
- HDU2689 Sort it (樹狀陣列求逆序數)陣列
- HDU 2689 【歸併排序求逆序對】排序
- HDU 1394 Minimum Inversion Number (樹狀陣列求逆序數)陣列
- 樹狀陣列和逆序對陣列
- hdu 3874 樹狀陣列陣列
- POJ 2299-Ultra-QuickSort(樹狀陣列求逆序數)UI陣列
- hdu 5147 樹狀陣列陣列
- hdu 4836 The Query on the Tree(線段樹or樹狀陣列)陣列
- HDU 1556 Color the ball(線段樹|樹狀陣列)陣列
- POJ 3067-Japan(樹狀陣列-逆序數)陣列
- hdu4325 樹狀陣列+離散化陣列
- hdu 4368 樹狀陣列 離線維護陣列
- HDU 1166 敵兵佈陣 (樹狀陣列)陣列
- HDU 1166 敵兵佈陣(樹狀陣列)陣列
- LeetCode C++ 劍指 Offer 51. 陣列中的逆序對【歸併排序/樹狀陣列/線段樹】LeetCodeC++陣列排序
- 陣列中的逆序對陣列
- HDU 1541 & POJ 2352 Stars (樹狀陣列)陣列
- HDU4843Wow! Such Sequence!(樹狀陣列寫法)陣列
- 歸併排序思想應用之----求陣列中的逆序對排序陣列
- 樹狀陣列陣列
- HDU 6274 Master of Sequence(思維+樹狀陣列+二分)AST陣列
- HDU5419Victor and Toys(樹狀陣列+數學期望)陣列
- hdu4417 樹狀陣列(求指定區間比指定數小的數的個數)陣列
- 解析樹狀陣列陣列
- HDU 1556【區間更新+單點查詢 樹狀陣列】陣列
- 陣列元素逆序陣列
- HDU 5862 Counting Intersections(樹狀陣列+掃描線+離散化)陣列
- HDU5147 Sequence II(樹狀陣列+字首和+字尾和)陣列
- HDU4991 Ordered Subsequence (dp+樹狀陣列+離散化)陣列
- 歸併排序-陣列中的逆序對排序陣列
- 【劍指offer】陣列中的逆序對陣列
- 樹狀陣列詳解陣列
- 樹狀陣列基礎陣列
- poj 2481 樹狀陣列陣列
- 二維樹狀陣列陣列
- 求區間不同數的個數【樹狀陣列求解】陣列
- 【樹狀陣列 單點修改,區間求值】hdu 1166 敵兵佈陣陣列
- 樹狀陣列模板題 & (樹狀陣列 1:單點修改,區間查詢)陣列