1.题目描述:
一种做法是前缀和思想
比如原先数据为000000000
我要对第3到8数全部加1
正常写法是for 3...8,复杂度是O(N),前缀和操作只要3处+1,9处-1,那么就是00100000-10
那么对数据求一遍前缀和就是0011111100
这里前缀和查询复杂度还是O(N),还可以用BIT(树状数组)优化到logN,这个代码以后补。
线段树也是这个思想,对l和r内区间进行update,维护父亲为儿子的和,最后输出t[1].w就行。
4.AC代码:
#include <bits/stdc++.h> #define INF 0x3f3f3f3f #define maxn 200100 #define lson root << 1 #define rson root << 1 | 1 #define N 1111 #define eps 1e-6 #define pi acos(-1.0) #define e exp(1.0) using namespace std; const int mod = 1e9 + 7; typedef long long ll; typedef unsigned long long ull; struct tree { int l, r, w; } t[maxn * 4]; int ans[maxn]; void build(int l, int r, int root) { t[root].l = l; t[root].r = r; t[root].w = 0; if (l == r) { // scanf("%d", &t[root].w); return; } int mid = l + r >> 1; build(l, mid, lson); build(mid + 1, r, rson); // pushup(root); } void update(int val, int l, int r, int root) { if (t[root].l == l && t[root].r == r) { t[root].w += val; return; } int mid = t[root].l + t[root].r >> 1; if (l > mid) update(val, l, r, rson); else if (r <= mid) update(val, l, r, lson); else { update(val, l, mid, lson); update(val, mid + 1, r, rson); } // pushup(root); } void query(int root) { for (int i = t[root].l; i <= t[root].r; i++) ans[i] += t[root].w; if (t[root].l != t[root].r) { query(lson); query(rson); } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); long _begin_time = clock(); #endif int n; while (~scanf("%d", &n), n) { build(1, n, 1); for (int i = 0; i < n; i++) { int a, b; scanf("%d%d", &a, &b); update(1, a, b, 1); } fill(ans, ans + n + 1, 0); query(1); for (int i = 1; i <= n; i++) if (i == 1) printf("%d", ans[i]); else printf(" %d", ans[i]); puts(""); } #ifndef ONLINE_JUDGE long _end_time = clock(); printf("time = %ld ms.", _end_time - _begin_time); #endif return 0; }