HDU 3333 Turing Tree (Tree array | Line Segment Tree)
Question: Given a range, q queries, and the sum of all non-repeated numbers in each query.
Idea: You can consider using a tree array.
Read all queries first, and do it offline. All queries are sorted in ascending order by the right endpoint.
Then, we traverse this interval from the first element of the given interval, and update the last position of each element in this process, add a [I] to the current position and subtract a [I] From the lastpos position.
That is to say, each step retains the duplicate element value closest to the current position, and the rest is set to zero. This will certainly ensure that the answer is correct,
If this position is exactly the right endpoint of a query, We will output the sum of the modified range values.
#include
#include
#include
#include
#include
#include #include
#include
#include
#include
#include
#include
#include
#define eps 1e-6 #define LL long long #define pii (pair
)//#pragma comment(linker, /STACK:1024000000,1024000000) using namespace std; const int maxn = 30000 + 300;const int maxq = 100000+1000;//const int INF = 0x3f3f3f3f;int n, q;int a[maxn], lastpos[maxn];LL C[maxn];map
Hash;int ha;struct Query {int l, r, id;bool operator < (const Query& A) const {return r < A.r;}} query[maxq];LL ans[maxq];int lowbit(int x) {return (x&(-x));} LL sumv(int x) {LL ret = 0;while(x > 0) {ret += C[x]; x -= lowbit(x);}return ret;}void add(int x, int d) {while(x <= n) {C[x] += d; x += lowbit(x);}}int dis(int x) {if(!Hash.count(x)) return Hash[x] = ++ha;return Hash[x];} void init() {ha = 0;Hash.clear();memset(lastpos, 0, sizeof(lastpos));memset(C, 0, sizeof(C));} int main() {//freopen(input.txt, r, stdin);int T; cin >> T;while(T--) {init();cin >> n;for(int i = 1; i <= n; i++) scanf(%d, &a[i]);cin >> q;for(int i = 0; i < q; i++) {int u, v; scanf(%d%d, &u, &v);query[i].l = u;query[i].r = v;query[i].id = i;}sort(query, query+q);int cnt = 0;for(int i = 1; i <= n; i++) {if(!lastpos[dis(a[i])]) add(i, a[i]), lastpos[dis(a[i])] = i;else {add(i, a[i]);add(lastpos[dis(a[i])], -a[i]);lastpos[dis(a[i])] = i;}while(cnt