线段树模版题,存个模板
1 #include <iostream> 2 #include <cstdio> 3 #include <fstream> 4 #include <algorithm> 5 #include <cmath> 6 #include <deque> 7 #include <vector> 8 #include <queue> 9 #include <string> 10 #include <cstring> 11 #include <map> 12 #include <stack> 13 #include <set> 14 #define LL long long 15 #define eps 1e-8 16 #define INF 0x3f3f3f3f 17 #define MAXN 100005 18 using namespace std; 19 int sum[MAXN * 3], add[MAXN * 3]; 20 void pushup(int t){ 21 sum[t] = sum[t << 1] + sum[t << 1 | 1]; 22 } 23 void pushdown(int t, int x){ 24 if (add[t]){ 25 add[t << 1] += add[t]; 26 add[t << 1 | 1] += add[t]; 27 sum[t << 1] += ((x + 1) >> 1)* add[t]; 28 sum[t << 1 | 1] += (x >> 1) * add[t]; 29 add[t] = 0; 30 } 31 } 32 void update(int L, int R, int t, int p, int q, int x){ 33 if (p <= L && q >= R){ 34 sum[t] += (R - L + 1) * x; 35 add[t] += x; 36 return; 37 } 38 39 pushdown(t, R - L + 1); 40 int mid = (L + R) >> 1; 41 if (p <= mid){ 42 update(L, mid, t << 1, p, q, x); 43 } 44 if (q > mid){ 45 update(mid + 1, R, t << 1 | 1, p, q, x); 46 } 47 pushup(t); 48 } 49 int query(int L, int R, int t, int p, int q){ 50 if (p <= L && q >= R){ 51 return sum[t]; 52 } 53 pushdown(t, R - L + 1); 54 int mid = (L + R) >> 1; 55 int res = 0; 56 if (p <= mid){ 57 res += query(L, mid, t << 1, p, q); 58 } 59 if (q > mid){ 60 res += query(mid + 1, R, t << 1 | 1, p, q); 61 } 62 return res; 63 } 64 int main() 65 { 66 #ifndef ONLINE_JUDGE 67 freopen("in.txt", "r", stdin); 68 //freopen("out.txt", "w", stdout); 69 #endif // OPEN_FILE 70 int n; 71 while (~scanf("%d", &n) && n){ 72 memset(sum, 0, sizeof(sum)); 73 memset(add, 0, sizeof(add)); 74 int x, y; 75 for (int i = 1; i <= n; i++){ 76 scanf("%d%d", &x, &y); 77 update(1, n, 1, x, y, 1); 78 } 79 for (int i = 1; i < n; i++){ 80 printf("%d ", query(1, n, 1, i, i)); 81 } 82 printf("%d\n", query(1, n, 1, n, n)); 83 } 84 }
时间: 2024-10-17 16:38:35