线段树#12被卡TLE,求助
查看原帖
线段树#12被卡TLE,求助
249422
TinyMirror1楼主2020/9/18 13:41
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 5e4 + 1;
string s;
struct node {
	int cnt[26], len, lazy;
	void clear() {
		memset(cnt, 0, sizeof(cnt));
	}
} T[maxn << 2];
void update(node &fa, node &lson, node &rson) {
	for (int i = 0; i < 26; i++) {
		fa.cnt[i] = lson.cnt[i] + rson.cnt[i];
	}
}
void pushdown(int id) {
	int l = id << 1, r = id << 1 | 1;
	int k = T[id].lazy;
	if (k != -1) {
		T[l].lazy = T[r].lazy = T[id].lazy;
		T[l].clear(); T[r].clear();
		T[l].cnt[k] = T[l].len;
		T[r].cnt[k] = T[r].len;
	}
	T[id].lazy = -1;
}
void build(int id, int l, int r) {
	T[id].lazy = -1;
	T[id].len = r - l + 1;
	if (l == r) {
		T[id].cnt[s[l - 1] - 'a'] = 1;
		return;
	}
	int mid = (l + r) >> 1;
	build(id << 1, l, mid);
	build(id << 1 | 1, mid + 1, r);
	update(T[id], T[id << 1], T[id << 1 | 1]);
}
void update(int id, int l, int r, int x, int y, int k) {
	if (x <= l && r <= y) {
		T[id].clear();
		T[id].lazy = k;
		T[id].cnt[k] = T[id].len;
		return;
	}
	pushdown(id);
	int mid = (l + r) >> 1;
	if (x <= mid) update(id << 1, l, mid, x, y, k);
	if (y > mid) update(id << 1 | 1, mid + 1, r, x, y, k);
	update(T[id], T[id << 1], T[id << 1 | 1]);
}
node query(int id, int l, int r, int x, int y) {
	if (x <= l && r <= y) {
		return T[id];
	}
	pushdown(id);
	node res[3];
	int mid = (l + r) >> 1, t = 0;
	if (x <= mid) res[++t] = query(id << 1, l, mid, x, y);
	if (y > mid) res[++t] = query(id << 1 | 1, mid + 1, r, x, y);
	if (t == 1) res[0] = res[1];
	if (t == 2) update(res[0], res[1], res[2]);
	return res[0];
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	int n;
	register int m;
	cin >> n >> m >> s;
	transform(s.begin(), s.end(), s.begin(), ::tolower);
	build(1, 1, n);
	while (m--) {
		char k;
		int op, x, y;
		cin >> op >> x >> y;
		if (op == 1) {
			cin >> k;
			if (k >= 'A' && k <= 'Z') {
				k = k + 'a' - 'A';
			}
			node t = query(1, 1, n, x, y);
			cout << t.cnt[k - 'a'] << '\n';
		}
		if (op == 2) {
			cin >> k;
			if (k >= 'A' && k <= 'Z') {
				k = k + 'a' - 'A';
			}
			update(1, 1, n, x, y, k - 'a');
		}
		if (op == 3) {
			node t = query(1, 1, n, x, y);
			for (int i = 0, l, r = x - 1; i < 26; ++i) {
				if (t.cnt[i] == 0) continue;
				l = r + 1, r = l + t.cnt[i] - 1;
				update(1, 1, n, l, r, i);
			}
		}
	}
	return 0;
} 
2020/9/18 13:41
加载中...