백준 알고리즘 7578번 : 공장

Zoo Da·2021년 11월 24일
0

백준 알고리즘

목록 보기
265/337
post-thumbnail

링크

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

sol1) 세그먼트 트리 + inversion counting

#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);
	}
};

int check[1000001];

int32_t main() {
  fastio;
  SegTree<int,20> ST;
  int n,ans = 0; cin >> n;
  for(int i = 1; i <= n; i++){
    int t; cin >> t;
    check[t] = i;
  }
  for(int i = 1; i <= n; i++){
    int t; cin >> t;
    ans += (check[t] - 1 - ST.Query(1,check[t] - 1));
    ST.Update(check[t], 1);
  }
  cout << ans << "\n";
}

2021-12-01 sol1과 동일 check배열 생성할 때 비트 연산으로 바꿈

#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;

int check[1 << 20];

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);
	}
};

int32_t main() {
  fastio;
  SegTree<int,20> ST;
  int n,r = 0; cin >> n;
  for(int i = 1; i <= n; i++){
    int t; cin >> t;
    check[t] = i;
  }
  for(int i = 1; i <= n; i++){
    int t; cin >> t;
    r += (check[t] - 1 - ST.Query(1, check[t] - 1));
    ST.Update(check[t], 1);
  }
  cout << r << "\n";
}

세그먼트 트리에서 inversion counting을 구하는 약간 응용된 문제입니다
첫번째 줄을 입력 받으면서 check배열에 해당 숫자가 몇번째로 나왔는지 저장하고 두번째 줄을 입력 받으면서 check배열의 inversion counting을 구해주면 됩니다.

profile
메모장 겸 블로그

0개의 댓글