Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
这代码要3s、求大师优化// // 3468_interval tree.cpp // OJ // // Created by Geoferry on 8/25/16. // Copyright © 2016 Geoferry. All rights reserved. // // Query the sum of a given range. #include <iostream> #include <cstring> #include <string.h> #include <stdio.h> #define MAX 100000 #define INF 0x3f3f3f3f using namespace std; struct Node{ int L, R; int Mid(){ return (L + R) / 2; } long long sum, val, var; }; Node node[4 * MAX + 10]; void build_tree(int root, int l, int r){ node[root].L = l; node[root].R = r; node[root].sum = node[root].var = 0; if(l != r){ build_tree((root << 1) + 1, l, node[root].Mid()); build_tree((root << 1) + 2, node[root].Mid() + 1, r); } } void insert(int root, long long i, long long v){ node[root].sum += v; if(node[root].L == node[root].R){ return; } else if(i <= node[root].Mid()){ return insert((root << 1) + 1, i, v); } else { return insert((root << 1) + 2, i, v); } } void update(int root, int l, int r, long long v){ if(node[root].L >= l && node[root].R <= r){ node[root].var += v; return; } if(l > node[root].Mid()){ node[root].sum += (r - l + 1) * v; update((root << 1) + 2, l, r, v); } else if(r <= node[root].Mid()){ node[root].sum += (r - l + 1) * v; update((root << 1) + 1, l, r, v); } else { node[root].sum += (node[root].Mid() - l + 1) * v; node[root].sum += (r - node[root].Mid()) * v; update((root << 1) + 1, l, node[root].Mid(), v); update((root << 1) + 2, node[root].Mid() + 1, r, v); } } long long query(int root, int l, int r){ long long tsum = 0; if(root != 0){ node[root].var += node[(root - 1) >> 1].var; } if(node[root].L >= l && node[root].R <= r){ return node[root].sum + node[root].var * (node[root].R - node[root].L + 1); } if(node[root].R < l || node[root].L > r){ return tsum; } tsum += query((root << 1) + 1, l, r); tsum += query((root << 1) + 2, l, r); node[root].sum += (node[root].R - node[root].L + 1) * node[root].var; node[root].var = 0; return tsum; } int main(){ int n, q, t1, t2; long long t3; char a; scanf("%d %d", &n, &q); build_tree(0, 1, n); for(int i = 1; i <= n; i++){ scanf("%lld", &t3); insert(0, i, t3); } while(q--){ // cout << "q: " << q << endl; scanf("%s", &a); // getchar(); // cout << "a: " << a << endl; if(a == 'C'){ scanf("%d %d %lld", &t1, &t2, &t3); update(0, t1, t2, t3); } if(a == 'Q'){ scanf("%d %d", &t1, &t2); t3 = query(0, t1, t2); printf("%lld\n", t3); } } // cout << "stop: " << node[0].L << endl; return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator