Cattle-off practice match 52 B Galahad (Fenwick tree)

Topic links: https://ac.nowcoder.com/acm/contest/1084/B

The meaning of problems

5E5 interval, 5e5 a query request [l, r] had occurred within the interval and number of

Thinking

1s time, Mo T team will obviously
we can ask sort r, maintain the position of the last occurrence of each number, and you can use the prefix and maintenance Fenwick tree

Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional>
#include<unordered_map>
    
#define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1

using namespace std;

typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL;

const db eps = 1e-6;
const int mod = 998244353;
const int maxn = 5e5+100;
const int maxm = 2e6+100;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0);

int n,m;
int a[maxn];
ll tree[maxn];
int lowbit(int x){return x&(-x);}
void add(int x, ll c){
    for(int i = x; i <= n; i+=lowbit(i)){
        tree[i]+=c;
    }
}
ll sum(int x){
    ll ans = 0;
    for(int i = x; i; i-=lowbit(i)){
        ans+=tree[i];
    }
    return ans;
}
struct node{
    int l, r;
    int id;
    node(){}
    node(int l, int r, int id):l(l),r(r),id(id){}
}q[maxn];
int cnt[maxn];
int id[maxn];
ll ans[maxn];
bool cmp(node a, node b){return a.r<b.r;}
int main(){
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
    }
    for(int i = 1; i <= m; i++){
        int l,r;
        scanf("%d %d", &l, &r);
        q[i]=node(l,r,i);
    }
    sort(q+1,q+1+m,cmp);
    int lst = 1;
    for(int i = 1; i <= m; i++){
        for(int j = lst; j <= q[i].r; j++){
            if(id[a[j]]){
                add(id[a[j]],-a[j]);
            }
            id[a[j]]=j;
            add(j,a[j]);
        }lst=q[i].r+1;
        ans[q[i].id]=sum(q[i].r)-sum(q[i].l-1);
    }
    for(int i = 1; i <= m; i++){
        printf("%lld\n",ans[i]);
    }
    return 0;
}
/*
3 3
1 1 1
1 3
2 3
2 2 
 */

Guess you like

Origin www.cnblogs.com/wrjlinkkkkkk/p/11527631.html