區間修改區間查詢 lazy標記

//區間修改,區間查詢
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string.h>
#define ll long long
using namespace std;

const int maxn = 100005;
struct node {
	ll sum;
	int lazy;
}T[maxn<<2];

void push_up(int root)
{
	T[root].sum = T[root << 1].sum + T[(root << 1) | 1].sum;
}

void push_down(int L, int R, int root)
{
	int mid = (L + R) >> 1;
	T[root << 1].sum = T[root].lazy*(mid - L + 1);
	T[root << 1 | 1].sum = T[root].lazy*(R - mid);
	T[root << 1].lazy = T[root << 1 | 1].lazy = T[root].lazy;
	T[root].lazy = 0;
}

void build(int l, int r, int root)
{
	if (l == r) {
		scanf("%d", &T[root].sum);
		return;
	}
	int mid=(l + r)>>1;
	build(l, mid, root<<1);
	build(mid + 1, r, root << 1 | 1);
	push_up(root);   //不能遺漏這一步
}

void update(int l, int r,int value, int L, int R, int root)
{
	if (l <= L&&r >= R) {
		T[root].lazy = value;
		T[root].sum = value*(R - L + 1);
		return;
	}
	int mid = (L + R) >> 1;
	if (T[root].lazy)push_down(L, R, root);
	if (r <= mid)update(l, r, value,L, mid, root << 1);
	else if (l > mid)update(l, r, value, mid + 1, R, root << 1 | 1);
	else {
		update(l, r, value, L, mid, root << 1);
		update(l, r, value, mid + 1, R, root << 1 | 1);
	}
	push_up(root);
}



int query(int l, int r, int L, int R, int root)
{
	if (l <= L&&r >= R)return T[root].sum;
	int mid = (L + R) >> 1;
	if (T[root].lazy)push_down(L, R, root);
	if (r <= mid)return query(l, r, L, mid, root<<1);
	else if (l > mid)return query(l, r, mid + 1, R, root<<1 | 1);
	return query(l, mid, L, mid, root << 1) + query(mid + 1, r, mid + 1, R, root << 1 | 1);
}

int main()
{
	int n, q;
	scanf("%d", &n);
	build(1, n, 1);
	scanf("%d", &q);
	int a, b, c, d;
	while (q--)
	{
		scanf("%d%d%d", &a, &b, &c);
		if (a)
		{
			scanf("%d", &d);
			update(b, c, d, 1, n, 1);
		}
		else printf("%d\n", query(b, c, 1, n, 1));
	}

	return 0;
}

發佈了7 篇原創文章 · 獲贊 3 · 訪問量 5558
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章