[ABC254Ex] Multiply or Divide by 2 题解

· · 题解

下位紫题,赢!

首先,看着是两种操作,其实是一种操作。

看着是只对一个集合操作,其实可以看做对两个集合操作。

对 A 集合进行 a_i \leftarrow a_i \times 2,等价于让 B 集合中某一个元素执行 b_i\leftarrow \lfloor \dfrac{b_i}{2} \rfloor。

于是全部转为除法操作,直接降为对数级别。

一个可以想到的贪心思路是,每次拿出两个集合的最大值比较,谁大了就对谁做除法,如果两个一样大就把他们消掉。

但也要想到,B 集合事实上是你不能动的。如果在一次比较中 B 集合的最大值是个奇数,那你是无法通过上述操作来使得 A,B 集合相等的,无解。

于是就可以快乐的拿 O(n\log n) 的做法水一道紫题啦!

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    int n, cnt = 0; cin >> n;
    priority_queue<int> A, B;
    for(int i = 1, t; i <= n; ++ i) cin >> t, A.push(t);
    for(int i = 1, t; i <= n; ++ i) cin >> t, B.push(t);
    while(A.size()) {
        auto u = A.top(), v = B.top(); A.pop(), B.pop();
        if(u > v) u >>= 1, A.push(u), B.push(v), ++ cnt;
        else if(u < v) (v & 1) ? (cout << -1, exit(0)) : (v >>= 1, A.push(u), B.push(v), ++ cnt, void(0));
    }
    cout << cnt;
}