zoukankan      html  css  js  c++  java
  • 树状数组

    树状数组

    lowbit : 求最低位的 (1) 以及后面的 (0) 所组成的十进制数

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<math.h>
    #include<algorithm>
    #define ll long long
    using namespace std;
    
    const ll maxn=5e5+10;
    ll n,m;
    
    struct node
    {
    	ll tree[maxn];
    	
    	ll lowbit(const ll x)
    	{
    		return x & -x;
    	}
    	void upd(ll p,ll w)
    	{
    		do tree[p]+=w;
    		while((p+=lowbit(p))<=n);
    	}
    	ll qry(ll p)
    	{
    		ll ret=0;
    		
    		do ret+=tree[p];
    		while((p-=lowbit(p))!=0);
    		
    		return ret;
    	}
    }bit;
    
    int main(void)
    {
    	scanf("%lld%lld",&n,&m);
    	
    	ll w,x,o;
    	
    	for(int i=1;i<=n;i++)
    	{
    		scanf("%lld",&x);
    		bit.upd(i,x);
    	}
    	
    	for(int i=1;i<=m;i++)
    	{
    		scanf("%lld",&o);
    		
    		if(o==1)
    		{
    			scanf("%lld%lld",&w,&x);
    			bit.upd(w,x);
    		}
    		else
    		{
    			scanf("%lld%lld",&w,&x);
    			printf("%lld
    ",bit.qry(x)-bit.qry(w-1));
    		}
    	}
    	
    	return 0;
    }
    

    求逆序对:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<math.h>
    #include<algorithm>
    #define ll long long
    using namespace std;
    
    const ll maxn=5e5+10;
    ll n,m,sum;
    ll a[maxn],b[maxn],c[maxn];
    
    inline ll lowbit(ll x)
    {
    	return x & (-x);
    }
    inline void upd(ll x,ll w)
    {
    	for( ;x<=n;x+=lowbit(x)) c[x]+=w;
    }
    inline ll qry(ll x)
    {
    	ll ret=0;
    	for( ;x;x-=lowbit(x)) ret+=c[x];
    	return ret;
    }
    inline void init_hash()
    {
    	scanf("%lld",&n);
    	
    	for(int i=1;i<=n;i++)
    	{
    		scanf("%lld",&a[i]);
    	}
    	memcpy(b+1,a+1,n*sizeof(ll));
    	sort(b+1,b+n+1);
    	ll *bg=b+1;
    	ll *ed=unique(b+1,b+n+1);
    	for(int i=1;i<=n;i++)
    	{
    		a[i]=lower_bound(bg,ed,a[i])-b;
    	}
    }
    inline void solve()
    {
    	for(int i=1;i<=n;i++) upd(i,1);
    	for(int i=1;i<=n;i++)
    	{
    		sum+=qry(a[i]-1);
    		upd(a[i],-1);
    	}
    	printf("%lld
    ",sum);
    }
    
    int main(void)
    {
    	init_hash();
    	solve();
    	return 0;
    }
    
  • 相关阅读:
    郁闷的出纳员 平衡二叉树(SBT)
    POJ 3225 Help with Intervals (线段树,区间成段更新)
    HDU 3038 How Many Answers Are Wrong (并查集)
    POJ 1733 Parity game (HASH+并查集)
    POJ 1417 True Liars(并查集+DP)
    POJ 2912 Rochambeau(枚举+并查集)
    UILabel添加发光效果
    TinyMCE integration with phpBB3
    快速重传与快速恢复算法
    TCP的超时与重传
  • 原文地址:https://www.cnblogs.com/jd1412/p/14087315.html
Copyright © 2011-2022 走看看