백준 알고리즘 2243번 : 사탕상자

Zoo Da·2021년 11월 22일
0

백준 알고리즘

목록 보기
261/337
post-thumbnail

링크

https://www.acmicpc.net/problem/2243

sol1) 세그먼트 트리 + 파라메트릭 서치

#pragma GCC optimize ("O3")
#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define int int64_t
using namespace std;

template<typename T = int64_t, size_t sz = 17, typename F = plus<T>>
struct SegTree {
	vector<T> tree; T t; F f{};
	SegTree(T t = T()) : tree(1 << sz + 1, t), t(t) {}
	explicit SegTree(T t, const F& f) : tree(1 << sz + 1, t), t(t), f(f) {}
	
	void Init() {
    for (int i = (1 << sz) - 1; i; i--) {
      tree[i] = f(tree[i << 1], tree[i << 1 | 1]);
    }
  }

	void Update(int i, T val) {
		--i |= 1 << sz; tree[i] += val;
		while (i >>= 1) tree[i] = f(tree[i << 1], tree[i << 1 | 1]);
	}
	T Query(int l, int r) {
		T L = t, R = t; --l |= 1 << sz, --r |= 1 << sz;
		while (l <= r) {
			if (l & 1) L = f(L, tree[l++]);
			if (~r & 1) R = f(tree[r--], R);
			l >>= 1, r >>= 1;
		}
		return f(L, R);
	}
  T sol(int k){
    int lo = 0,hi = 1000000;
    while(lo + 1 < hi){
      int mid = (lo + hi) / 2;
      if(Query(1, mid) < k) lo = mid;
      else hi = mid;
    }
    return hi;
  }
};

SegTree<int, 20> ST;

int32_t main() {
  fastio;
  int n; cin >> n;
  while(n--){
    int a,b,c; cin >> a;
    if(a == 1){
      cin >> b;
      int ans = ST.sol(b);
      cout << ans << "\n";
      ST.Update(ans, -1);
    }
    else if(a == 2){
      cin >> b >> c;
      ST.Update(b, c);
    }
  }
}
profile
메모장 겸 블로그

0개의 댓글