HDU 1556 Color the ball(线段树区间更新区间查询模板)

xiaoxiao2021-02-27  285

Problem Description N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?   Input 每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。 当N = 0,输入结束。   Output 每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。   Sample Input 3 1 1 2 2 3 3 3 1 1 1 2 1 3 0   Sample Output 1 1 1 3 2 1

/* 3 1 1 2 2 3 3 3 1 1 1 2 1 3 0 */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100005; int sum[maxn*4], lazy[maxn*4]; void pushdown(int root, int l, int r) { if(lazy[root]) { int mid = (l+r)/2; lazy[root*2] += lazy[root]; lazy[root*2+1] += lazy[root]; sum[root*2] += (mid-l+1)*lazy[root]; sum[root*2+1] += (r-(mid+1)+1)*lazy[root]; lazy[root] = 0; } } void update(int root, int l, int r, int i, int j, int val) { if(i <= l && j >= r) { lazy[root] += val; sum[root] += (r-l+1)*val; return ; } pushdown(root, l, r); int mid = (l+r)/2; if(mid >= i) update(root*2, l, mid, i, j, val); if(mid < j) update(root*2+1, mid+1, r, i, j, val); sum[root] = sum[root*2] + sum[root*2+1]; } int query(int root, int l, int r, int i, int j) { if(i <= l && j >= r) return sum[root]; pushdown(root, l, r); int mid = (l+r)/2, suml = 0, sumr = 0; if(mid >= i) suml = query(root*2, l, mid, i, j); if(mid < j) sumr = query(root*2+1, mid+1, r, i, j); return suml + sumr; } int main(void) { int n; while(~scanf("%d", &n) && n) { memset(lazy, 0, sizeof(lazy)); memset(sum, 0, sizeof(sum)); for(int i = 1; i <= n; i++) { int x, y; scanf("%d%d", &x, &y); update(1, 1, n, x, y, 1); } for(int i = 1; i <= n; i++) { if(i != 1) printf(" "); printf("%d", query(1, 1, n, i, i)); } printf("\n"); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-3292.html

最新回复(0)