程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU 3874 Necklace(樹狀數組)

HDU 3874 Necklace(樹狀數組)

編輯:C++入門知識

HDU 3874 Necklace(樹狀數組)


Problem Description Mery has a beautiful necklace. The necklace is made up of N magic balls. Each ball has a beautiful value. The balls with the same beautiful value look the same, so if two or more balls have the same beautiful value, we just count it once. We define the beautiful value of some interval [x,y] as F(x,y). F(x,y) is calculated as the sum of the beautiful value from the xth ball to the yth ball and the same value is ONLY COUNTED ONCE. For example, if the necklace is 1 1 1 2 3 1, we have F(1,3)=1, F(2,4)=3, F(2,6)=6.

Now Mery thinks the necklace is too long. She plans to take some continuous part of the necklace to build a new one. She wants to know each of the beautiful value of M continuous parts of the necklace. She will give you M intervals [L,R] (1<=L<=R<=N) and you must tell her F(L,R) of them.
Input The first line is T(T<=10), representing the number of test cases.
For each case, the first line is a number N,1 <=N <=50000, indicating the number of the magic balls. The second line contains N non-negative integer numbers not greater 1000000, representing the beautiful value of the N balls. The third line has a number M, 1 <=M <=200000, meaning the nunber of the queries. Each of the next M lines contains L and R, the query.
Output For each query, output a line contains an integer number, representing the result of the query.
Sample Input
2
6
1 2 3 4 3 5
3
1 2
3 5
2 6
6
1 1 1 2 3 5
3
1 1
2 4
3 5

Sample Output
3
7
14
1
3
6

題意:給你一串數字,讓你求區間[l,r]內的和,要求重復數字只求一次。

樹狀數組做法:大家肯定會想到離線,但是離線後排序如何排,這裡有一個思路:

由於要去重,我們考慮將詢問按右區間從小到大排序,對於詢問,我們逐個去掉前面

重復的值,只保留當前的。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
typedef long long LL;
const int maxn=50000+100;
const int maxm=200000+100;
LL c[maxn], ans[maxm];
int pre[maxn],hash[1000000+10];
struct node{
    int l,r;
    int id;
}q[maxm];
int num[maxn];
int t,n,m;
int lowbit(int x)
{
    return x&(-x);
}
void update(int x,LL w)
{
    while(x0)
    {
        s+=c[x];
        x-=lowbit(x);
    }
    return s;
}
int cmp(node l1,node l2)
{
    return l1.r

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved