樹狀數組 poj2299

題目大意就是要你求給定數組的逆序對,逆序對的個數即爲交換的次數。

我們先進性離散化,在將數一個個放到樹狀數組中去。我們更新操作是將從大區間向小區間更新,更新完之後立馬查詢當前的大區間(即爲前面有多少個數大於當前數)

 

#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#include <bitset>
#define  LL long long
#define  ULL unsigned long long
#define mod 10007
#define INF 0x7ffffff
#define mem(a,b) memset(a,b,sizeof(a))
#define MODD(a,b) (((a%b)+b)%b)
using namespace std;
const int maxn = 3e6 + 5;
int a[maxn],sum[maxn],n;
vector<int> V;
int getId(int x){return lower_bound(V.begin(),V.end(),x) - V.begin() + 1;}
int lowbit(int x){return x&(-x);}
void upDate(int x,int t)
{
    while(x > 0){
      sum[x]+=t;
      x-=lowbit(x);
    }
    return ;
}
LL query(int x)
{
    LL ans = 0;
    while(x <= n){
      ans+=sum[x];
      x += lowbit(x);
    }
    return ans;
}
int main()
{
    while(~scanf("%d",&n) && n){
      mem(sum,0);
        V.clear();
      for(int i = 1; i <= n; i++) {scanf("%d",&a[i]);V.push_back(a[i]);}
      sort(V.begin(),V.end());
      V.erase(unique(V.begin(),V.end()),V.end());
      LL ans = 0;
      for(int i = 1; i <= n; i++){
        upDate(getId(a[i]),1);
        ans += query(getId(a[i]));
      }
      printf("%lld\n",ans - n);
    }




    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章