- 문제 링크 : boj.kr/31830
- 난이도 : P4
- 태그 : 세그먼트 트리
코드
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define INF 0x7FFFFFFF
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;
template<typename T>
class segTree {
private:
ll n;
T id;
T(*merge)(T, T);
vector<T> tree;
public:
segTree(ll n, T id, T(*merge)(T, T)) {
this->n = n;
this->id = id;
this->merge = merge;
tree.resize(n*4);
}
void update(ll idx, T value) {
_update(1, 1, n, idx, value);
}
T query(ll l, ll r) {
return _query(1, 1, n, l, r);
}
private:
void _update(int node, int s, int e, int idx, T value) {
if(idx < s || e < idx) return;
if(s == e) {
tree[node] = value;
return;
}
_update(node*2, s, (s+e)/2, idx, value);
_update(node*2+1, (s+e)/2+1, e, idx, value);
tree[node] = merge(tree[node*2], tree[node*2+1]);
}
T _query(int node, int s, int e, int l, int r) {
if(l > e || r < s) return id;
if(l <= s && e <= r) return tree[node];
T lq = _query(node*2, s, (s+e)/2, l, r);
T rq = _query(node*2+1, (s+e)/2+1, e, l, r);
return merge(lq, rq);
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n, q;
cin >> n >> q;
string str;
cin >> str;
vector<int> arr(n+1);
for(int i = 1; i < n; i++) {
arr[i+1] = (str[i]-str[i-1] + 26) % 26;
}
arr[1] = 1;
segTree<int> s(n, 0, [](int a, int b){return a+b;});
for(int i = 1; i <= n; i++) {
if(arr[i] != 0) s.update(i, 1);
}
while(q--) {
int t, l, r;
cin >> t >> l >> r;
if(t == 1) cout << s.query(1, r) - s.query(1, l) + 1 << "\n";
else {
if(l != 1) {
arr[l] = (arr[l] + 1) % 26;
s.update(l, arr[l] != 0);
}
if(r != n) {
arr[r+1] = (arr[r+1] + 25) % 26;
s.update(r+1, arr[r+1] != 0);
}
}
}
return 0;
}
풀이
값을 인접한 알파벳의 차이로 다루어준다.
구간에 걸리는 쿼리를 구간의 양 쪽 끝 차이로 변환할 수 있다.
728x90
'PS' 카테고리의 다른 글
BOJ 1893 : 시저 암호 (0) | 2024.10.09 |
---|---|
BOJ 1498 : 주기문 (2) | 2024.10.08 |
BOJ 23833 : F1ow3rC0n (2) | 2024.10.06 |
BOJ 23024 : 보트 정박 (1) | 2024.10.05 |
BOJ 22959 : 신촌 수열과 쿼리 (3) | 2024.10.04 |