CF1728C Digital Logarithm C++ 题解

· · 题解

题意

令 f(x) 表示十进制下不含前导零时,x 的位数。给定长度为 n(1\leqslant \sum n \leqslant 2\times 10^5) 的数组 a, b(1\leqslant a_i,b_i < 10^9),每一次操作选择 a 或 b 中的一个数 y,令 y = f(y)。求最少多少次操作可以使得任意排列后,a 和 b 完全相同。

思路

显然若 a,b 中有相同的数,可以直接将它们配对。因此先把所有能配对的数从 a,b 中删去。剩下的数中,所有大于等于 10 的数不通过操作必定不能配对,因此把这些数进行一次操作。

接下来所有的数都在 1\sim 9。和第一步相似,把所有相同的数配对删去。删去后剩下一些数,这些数必须变成 1。因此再把这些数变成 1 即可。

通过 multiset 实现删除 O(n\log n)。也可以通过双指针实现,时间复杂度降到 O(n)。\log_{10}10^9 实在是太小了,而且并不是每一次操作都要算,所以直接忽略。

这里给出略丑的 multiset 实现。

AC code record

#include <bits/stdc++.h>
#define rep1(i, l, r) for (int i = l; i <= int(r); ++i)
#define rep2(i, l, r) for (int i = l; i >= int(r); --i)
#define ptc putchar
#define il inline
#define eb emplace_back
#define mp make_pair
#define fst first
#define snd second
#define .....
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2e5 + 10, inf = ~0U >> 2, INF = ~0U >> 1;
const int LOGN = log2(MAXN) + 1;
const int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
namespace stupid_lrc {
    template <typename T> il bool read(T &x)

    il int read()

    template <typename T> il bool read(pair <T, T> &x) 

    template <typename T, typename ...L>
    il bool read(T &x, L &...y)

    template <typename T> il void write(T x)

    template <typename T> il void write(T x, char ch) 

    template <typename T> il void write(pair <T, T> x) 

    template <typename T> il T my_max(const T &x, const T &y)

    template <typename T> il T my_min(const T &x, const T &y)

    template <typename T> il T lowbit(const T &x)
}
using namespace stupid_lrc;
// 奇妙缺省源......
int n, a[MAXN], b[MAXN];
multiset <int> t1, t2;
vector <int> k1, k2;

il int get(int k) {
    if (!k) return 1;
    int cnt = 0;
    while (k) ++cnt, k /= 10;
    return cnt;
}

int main() {
    for (int T = read(); T--; ) {
        t1.clear(); t2.clear();
        read(n); rer(i, 1, n, a); rer(i, 1, n, b);
        rep1(i, 1, n) t1.insert(a[i]), t2.insert(b[i]);
        int ans = 0;
        for (auto p = t1.begin(); p != t1.end(); ) {
            auto m = t2.find(*p);
            if (m != t2.end()) {
                t2.erase(m);
                p = t1.erase(p);
            } else ++p;
        }
        k1.clear(); k2.clear();
        for (auto v : t1) k1.eb(v);
        for (auto v : t2) k2.eb(v);
        for (auto &v : k1) if (v >= 10) v = get(v), ++ans;
        for (auto &v : k2) if (v >= 10) v = get(v), ++ans;
        t1.clear(); t2.clear();
        for (auto v : k1) t1.insert(v);
        for (auto v : k2) t2.insert(v);
        for (auto p = t1.begin(); p != t1.end(); ) {
            auto m = t2.find(*p);
            if (m != t2.end()) {
                t2.erase(m);
                p = t1.erase(p);
            } else ++p;
        }
        for (auto v : t1) ans += v != 1;
        for (auto v : t2) ans += v != 1;
        write(ans, '\n');
    }
    rout;
}