CF580E Kefa and Watch (線段樹維護雜湊)

Fire_Raku發表於2024-06-30

CF580E Kefa and Watch

線段樹維護雜湊

雜湊可以合併,所以可以想到用線段樹維護雜湊值。預處理 \(f_{i,j}\) 表示數字 \(i\) 長度為 \(j\) 時的雜湊值,實現區間覆蓋,區間查詢。

詢問等價於判斷 \(s[l\cdots r-d]\)\(s[l+d\cdots r]\) 是否相等,區間查詢即可。需要特判迴圈節是本身的情況。

複雜度 \(O(n\log n)\)

#include <bits/stdc++.h>
#define pii std::pair<int, int>
#define fi first
#define se second
#define pb push_back

using i64 = long long;
using ull = unsigned long long;
const i64 iinf = 0x3f3f3f3f, linf = 0x3f3f3f3f3f3f3f3f;
const int N = 1e5 + 10, p = 20242024, mod = 1234567891;

int n, m, k;
std::string s;
i64 f[10][N], pw[N];

struct SEG {
	i64 h, lzy;
	int len;
} t[N << 2];
void pushup(int u) {
	t[u].h = (t[u << 1].h * pw[t[u << 1 | 1].len] + t[u << 1 | 1].h) % mod;
	t[u].len = t[u << 1].len + t[u << 1 | 1].len;
}
void build(int u, int l, int r) {
	t[u].lzy = -1;
	if(l == r) {
		t[u].len = 1;
		t[u].h = s[l];
		return;
	}
	int mid = (l + r) >> 1;
	build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
	pushup(u);
}
void mdf(int u, int x) {
	t[u].h = f[x][t[u].len];
	t[u].lzy = x;
}
void pd(int u) {
	if(t[u].lzy == -1) return;
	mdf(u << 1, t[u].lzy), mdf(u << 1 | 1, t[u].lzy);
	t[u].lzy = -1;
}
void upd(int u, int l, int r, int L, int R, int x) {
	if(L <= l && r <= R) {
		mdf(u, x);
		return;
	}
	int mid = (l + r) >> 1; pd(u);
	if(L <= mid) upd(u << 1, l, mid, L, R, x);
	if(R > mid) upd(u << 1 | 1, mid + 1, r, L, R, x);
	pushup(u);
}
SEG qry(int u, int l, int r, int L, int R) {
	if(L <= l && r <= R) return t[u];
	int mid = (l + r) >> 1; pd(u);
	if(R <= mid) return qry(u << 1, l, mid, L, R);
	if(L > mid) return qry(u << 1 | 1, mid + 1, r, L, R);
	SEG ret = {0, 0, 0}, ls = qry(u << 1, l, mid, L, R), rs = qry(u << 1 | 1, mid + 1, r, L, R);
	ret.h = (ls.h * pw[rs.len] % mod + rs.h) % mod, ret.len = ls.len + rs.len;
	return ret;
}
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
	std::cin >> n >> m >> k >> s;
	s = '#' + s;

	pw[0] = 1;
	for(int i = 1; i <= n; i++) pw[i] = pw[i - 1] * p % mod;
	build(1, 1, n);
	for(int i = 0; i < 10; i++) {
		for(int j = 1; j <= n; j++) {
			f[i][j] = (f[i][j - 1] * p % mod + (i + '0')) % mod;
		}
	}

	int q = m + k;
	while(q--) {
		int op, l, r, c;
		std::cin >> op >> l >> r >> c;
		if(op == 1) {
			upd(1, 1, n, l, r, c);
		} else {
			if(c == r - l + 1 || qry(1, 1, n, l, r - c).h == qry(1, 1, n, l + c, r).h) std::cout << "YES\n";
			else std::cout << "NO\n";
		} 
	}

	return 0;
}

相關文章