I was writing this task https://codeforces.com/contest/459/problem/D on codeforces and my solution uses trees, but after running update function every element goes back to 0.
#include<bits/stdc++.h>
using namespace std;
int n,k,a[1000009],ans1[1000009],ans2[1000009],fans,w;
map<int,int> pref;
struct Node{
    Node *L,*R;
    int Sum;
    Node()
    {
        Sum=0;
        L=NULL;
        R=NULL;
    }
}*root = new Node();
void update(Node *it,int l,int r,int q)
{
    if(it==NULL) it = new Node();
    if(q<l || q>r) return;
    it->Sum ++;
    cout<<l<<" "<<r<<" "<<q<<" "<<it->Sum<<endl;
    if(l==r) return;
    update(it->L,l,(l+r)/2,q);
    update(it->R,(l+r)/2+1,r,q);
    
}
void findans(Node *it,int l,int r,int L,int R)
{
    if(it==NULL) 
    {
        it = new Node();
        cout<<"1 ";
    }
    cout<<l<<" "<<r<<" "<<L<<" "<<R<<" "<<it->Sum<<endl;
    if(l>=L && r<=R) w+=it->Sum;
    if(l!=r) if(l<=R && r>=L)
    {
        findans(it->L,l,(l+r)/2,L,R);
        findans(it->R,(l+r)/2+1,r,L,R);
    }
}
int main()
{
    cin>>n;
    for(k=1;k<=n;k++)
    {
        cin>>a[k];
        pref[a[k]]++;
        ans1[k]=pref[a[k]];
    }
    
    pref.clear();
    for(k=n;k>=1;k--)
    {
        pref[a[k]]++;
        ans2[k]=pref[a[k]];
    }
    
    for(k=n;k>=1;k--)
    {
        w=0;
        findans(root,1,n,1,ans1[k]-1);
        fans+=w;
        update(root,1,n,ans2[k]);
        cout<<endl;
    }
    cout<<fans;
}
this is the code(I have extra couts so I could find out where was the problem). also root gets updated normally but every other nodes -> sum goes back to 0 ( sorry for my bad english )
