PS
BOJ 14463 : 소가 길을 건너간 이유 9
lickelon
2024. 9. 27. 23:35
- 문제 링크 : boj.kr/14463
- 난이도 : 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;
cin >> n;
segTree<int> s(n*2, 0, [](int a, int b){return a+b;});
vector<pii> arr(n);
for(int i = 1; i <= n*2; i++) {
int input;
cin >> input;
input--;
if(arr[input].first == 0) {
arr[input].first = i;
continue;
}
arr[input].second = i;
if(arr[input].first > arr[input].second)
swap(arr[input].first, arr[input].second);
}
sort(all(arr));
ll ans = 0;
for(int i = 0; i < n; i++) {
ans += s.query(arr[i].first, arr[i].second);
s.update(arr[i].second, 1);
}
cout << ans;
return 0;
}
풀이
소 A의 정보를 Ax, Ay (Ax < Ay)로 표현하면 소 A와 소 B가 만날 조건은 $Ax < Bx < Ay < By$ 또는 $Bx < Ax < By < Ay$이다.
$Ax < Bx$라고 하면 $Ax < Bx < Ay < By$만 가능하다.
x를 오름차순으로 정렬하고, 세그먼트 트리를 이용하여 y값을 업데이트하면 조건을 만족하는 소의 수를 쉽게 셀 수 있다.
728x90