Jackiesteed

www.github.com/jackiesteed

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

线段树,懒操作

题目传送门

附代码:

View Code
  1 #include <iostream>
2 #include <fstream>
3 #include <algorithm>
4 #include <cstdio>
5 #include <cstring>
6 #include <cmath>
7 #include <cstdlib>
8
9 using namespace std;
10
11 typedef long long LL;
12
13 typedef struct node
14 {
15 int left, right, mid;
16 LL val, inc;
17 }node;
18
19
20 LL val[210000];
21 int N, M;
22 node tree[1000000];
23
24 void build(int l, int r, int idx)
25 {
26 tree[idx].left = l, tree[idx].right = r;
27 tree[idx].mid = (l + r) / 2;
28 tree[idx].inc = 0;
29 if(l == r)
30 {
31 tree[idx].val = val[l];
32 return ;
33 }
34 build(l, tree[idx].mid, idx << 1);
35 build(tree[idx].mid + 1, r, (idx << 1) + 1);
36 tree[idx].val = min(tree[idx << 1].val, tree[(idx << 1) + 1].val);
37 }
38
39 void inc(int l, int r, LL v, int idx)
40 {
41 if(l == tree[idx].left && r == tree[idx].right)
42 {
43 tree[idx].inc += v;
44 tree[idx].val += v;
45 return;
46 }
47 if(0 != tree[idx].inc)
48 {
49 inc(tree[idx].left, tree[idx].mid, tree[idx].inc, idx << 1);
50 inc(tree[idx].mid + 1, tree[idx].right, tree[idx].inc, (idx << 1) + 1);
51 tree[idx].inc = 0;
52 }
53
54 int mid = tree[idx].mid;
55
56 if(r <= mid)
57 {
58 inc(l, r, v, idx << 1);
59 }
60 else if(l > mid)
61 {
62 inc(l, r, v, (idx << 1) + 1);
63 }
64 else
65 {
66 inc(l, mid, v, idx << 1);
67 inc(mid + 1, r, v, (idx << 1) + 1);
68 }
69 tree[idx].val = min(tree[idx << 1].val, tree[(idx << 1) + 1].val);
70
71 }
72
73 LL query(int l, int r, int idx)
74 {
75 // printf("%d %d %d\n", l, r, idx);
76 if(l == tree[idx].left && r == tree[idx].right)
77 {
78 return tree[idx].val;;
79 }
80 if(0 != tree[idx].inc)
81 {
82 inc(tree[idx].left, tree[idx].mid, tree[idx].inc, (idx << 1));
83 inc(tree[idx].mid + 1, tree[idx].right, tree[idx].inc, (idx << 1) + 1);
84 tree[idx].inc = 0;
85 }
86
87 int mid = tree[idx].mid;
88 if(r <= mid)
89 {
90 return query(l, r, idx << 1);
91 }
92 else if(l > mid)
93 {
94 return query(l, r, (idx << 1) + 1);
95 }
96 else
97 {
98 return min(query(l, mid, (idx << 1)), query(mid + 1, r, (idx << 1) + 1));
99 }
100 }
101
102 int main()
103 {
104 // freopen("input.txt", "r", stdin);
105 scanf("%d", &N);
106
107 for(int i = 0; i < N; i++)
108 scanf("%I64d", &val[i]);
109
110 build(0, N - 1, 1);
111
112 char str[1000];
113
114 scanf("%d\n", &M);
115
116 int l, r;
117 LL v;
118
119 while(M--)
120 {
121
122 gets(str);
123
124 if(3 == sscanf(str, "%d %d %I64d", &l, &r, &v))//inc
125 {
126 if(l > r)
127 {
128 inc(l, N - 1, v, 1);
129 inc(0, r, v, 1);
130 }
131 else
132 {
133 inc(l, r, v, 1);
134 }
135 }
136 else
137 {
138 LL res = 0;
139 if(l > r)
140 {
141 res = min(query(l, N - 1, 1), query(0, r, 1));
142 }
143 else
144 {
145 res = query(l, r, 1);
146 }
147 printf("%I64d\n", res);
148 }
149 }
150 return 0;
151 }

  

posted on 2011-07-30 21:40  Jackiesteed  阅读(219)  评论(0编辑  收藏  举报