树状数组 poj2299

编程入门 行业动态 更新时间:2024-10-08 00:33:09

<a href=https://www.elefans.com/category/jswz/34/1766397.html style=树状数组 poj2299"/>

树状数组 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;
}

 

更多推荐

树状数组 poj2299

本文发布于:2024-02-19 18:33:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1765306.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:树状   数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!