[codeforces | 树状数组]round1400 D. Zigzags

题目链接:super_Link
对树状数组的更新不了解可以看博客:博客地址
在这里插入图片描述
代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

#define debug(x) cout<<#x<<" is "<<x<<endl
#define pb push_back
const int N = 3000 + 5;
vector<int> g[N];
ll n,t;
ll a[N],c[N];
ll lowbit(ll x){
    
    
	return x&(-x);
}
void update(ll i,ll x){
    
    
	while(i <= n){
    
    
		c[i] += x;
		i += lowbit(i); 
	}
}
ll getsum(ll i){
    
    
	ll sum = 0;
	while(i > 0){
    
    
		sum += c[i];
		i -= lowbit(i);
	}
	return sum;
}
ll ans = 0;
int main(){
    
    
	scanf("%d",&t);
	while(t--){
    
    
		scanf("%d",&n);
		ans = 0;
		for(int i = 1;i <= n;i++){
    
    
			c[i] = 0;
			g[i].clear();
		}
		for(int i = 1;i <= n;i++){
    
    
			scanf("%d",&a[i]);
			g[a[i]].pb(i);
		}
		for(int i = 1;i <= n;i++){
    
    
			int low = lower_bound(g[a[i]].begin(),g[a[i]].end(),i) - g[a[i]].begin();
			for(int j = 0;j < low;j++){
    
    
				ll res = getsum(g[a[i]][j]);
				ans += res;
			}
			for(int j = 0;j < low;j++){
    
    
				int l = g[a[i]][j] + 1 , r = i;
				update(l,1);
				update(r,-1);
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_20252251/article/details/108286738