[树状数组] Galahad

题意:求给定区间内不同数的和

经典例题https://vjudge.net/problem/HDU-3333


解题思路:

这两天有点傻,emmm

离线操作

扫一遍数组

对于重复的值树状数组维护最靠近当前坐标的那一个,等同于把之前重复的元素删掉。

这样再对询问进行前缀和计算则只能计算到最靠近当前点的每个只出现一次的元素

不在区间的自然查询不到,树状数组快速求前缀和记录答案输出即可


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 100;
  
struct node
{
    ll fst, lst, id;
}arr[MAXN];

ll num[MAXN] = {0}, ans[MAXN] = {0};

bool cmp(node a, node b) { return a.lst == b.lst ? a.fst <= b.fst : a.lst <= b.lst; } 

struct bit
{
	ll c[MAXN], N;
	
	bit() {}
	bit(int n) { N = n; fill(c, c + N + 1, 0);	}
	
	int lowbit(int x) { return x & -x; }
	
	void update(int pos, ll val)
	{
		for( ;pos <= N; pos += lowbit(pos))
			c[pos] += val;
	}
	
	ll ask(int pos)
	{
		ll ret = 0;
		for( ;pos; pos -= lowbit(pos))
			ret += c[pos];
		return ret;
	}
};

int lst[MAXN] = {0};

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	    
    ll n, m;
      
    cin >> n >> m;
    
    bit BT(n);

    for(int i = 1; i <= n; ++i)
        cin >> num[i];
      
    for(int i = 0; i < m; ++i)
    {
        cin >> arr[i].fst >> arr[i].lst;
        arr[i].id = i;
    }
      
    sort(arr, arr + m, cmp);
    
    int rp = 0;
    
    for(int i = 1; i <= n && rp < m; ++i)
    {
    	if(lst[num[i]])
    		BT.update(lst[num[i]], -num[i]);
    		
		BT.update(i, num[i]);
		lst[num[i]] = i;
		
		while(i == arr[rp].lst)
		{
			ans[arr[rp].id] = BT.ask(i) - BT.ask(arr[rp].fst - 1);
			++rp;
		}
	}
      
    for(int i = 0; i < m; ++i)
        cout << ans[i] << '\n';
         
    return 0;
}

 

posted @ 2019-09-15 17:41  张浦  阅读(104)  评论(0编辑  收藏  举报