1. 程式人生 > >[Codevs] 1688 求逆序對

[Codevs] 1688 求逆序對

dev close wrapper pro lld cti none des put

1688 求逆序對

時間限制: 1 s 空間限制: 128000 KB 題目等級 : 黃金 Gold 題目描述 Description

給定一個序列a1,a2,…,an,如果存在i<j並且ai>aj,那麽我們稱之為逆序對,求逆序對的數目

數據範圍:N<=105。Ai<=105。時間限制為1s。

輸入描述 Input Description

第一行為n,表示序列長度,接下來的n行,第i+1行表示序列中的第i個數。

輸出描述 Output Description

所有逆序對總數.

樣例輸入 Sample Input

4

3

2

3

2

樣例輸出 Sample Output

3

分析 Analysis

裸題,數據還水。

其實是我拿來練樹狀數組求逆序對的= =。

代碼 Code

技術分享
 1 #include<cstdio>
 2 #include<iostream>
 3 #define maxn 1010101 
 4 #define lowbit(x) (-x&x)
 5 using namespace std;
 6 
 7
long long n,t[maxn],a[maxn],maxx = 0,tot; 8 9 void add(long long p){ 10 while(p <= maxx){ 11 t[p]++; 12 p += lowbit(p); 13 } 14 } 15 16 long long sum(long long p){ 17 long long ans = 0; 18 while(p){ 19 ans += t[p]; 20 p -= lowbit(p);
21 } 22 return ans; 23 } 24 25 int main(){ 26 scanf("%lld",&n); 27 for(int i = 1;i <= n;i++){ 28 scanf("%lld",&a[i]); 29 maxx = max(maxx,a[i]); 30 } 31 32 for(int i = n;i >= 1;i--){ 33 tot += sum(a[i]-1); 34 add(a[i]); 35 } 36 37 printf("%lld",tot); 38 39 return 0; 40 }
點擊就送Leo_CT公仔!

[Codevs] 1688 求逆序對