[Solution] P1966 #NOIP2013 TG

· · 题解

P1966.

Changelog:简化题解,修复了 \LaTeX,更新代码。

给定两个序列 a_{1 \cdots n}, b_{1 \cdots n},每次操作可将任意序列中相邻两位置交换。

求:要使 \sum (a_i - b_i)^2 取最小值,所需最少操作次数。

--- $$\sum(a_i - b_i)^2 = \sum(a_i^2 + b_i^2 - 2 a_i b_i),$$ 上式取最小值等价于 $\sum a_i b_i$ 取最大值。 --- 若 $a_i \leqslant a_j$,$b_p \leqslant b_q$, 则 $$(a_i b_p + a_j b_q) - (a_i b_q + a_j b_p) = (a_i - a_j) (b_p - b_q) \geqslant 0,$$ 故 $a_i b_p + a_j b_q \geqslant a_i b_q + a_j b_p.

综上,应使 a, b 内部相对顺序一致。

比较直观地,要使操作次数最小,有一种可行方案是:只对 b 进行操作,使之内部相对顺序与 a 一致。

因为是相对顺序,所以我们可以先进行离散化,问题变为使 a, b 完全一致。

设 c_{a_i} = i,则 b_i 应该最终移到 b 中位置 c_{b_i}。

于是我们再进行一波处理:b_i \leftarrow c_{b_i}。

处理后,问题变为使 b_i 升序。

此时的操作次数即为 b 的逆序对数,可用归并或树状数组求出。

代码用树状数组求逆序对。

# include <cstdio>
# include <cstring>
# include <algorithm>

namespace Main {
    namespace Source {
        typedef unsigned int uint;
        template <const uint N>
        class Fenwick_tree {
            uint tree[N + 1];
            static inline const uint lowbit(const uint x) { return x bitand ~x + 1; }
        public:
            Fenwick_tree() { memset(tree, 0, sizeof tree); }
            inline const void modify(uint x) { while (x and x <= N) ++tree[x], x += lowbit(x); }
            inline const uint query(uint x)
            { uint r(0); while (x and x <= N) r += tree[x], x ^= lowbit(x); return r;}
        };
    }
    using namespace Source;
    enum { N = (const uint)1e5 };
    static const uint Mod(1e8 - 3);
    static uint n;
    static uint a[N], b[N], c[N];
    static Fenwick_tree<N> u;
    static uint ans;
    static inline const void discrete(uint a[N]) {
        static uint t[N];
        for (register uint i(0); i < n; ++i) t[i] = a[i];
        std::sort(&t[0], &t[n]);
        for (register uint i(0); i < n; ++i) a[i] = std::lower_bound(&t[0], &t[n], a[i]) - t;
    }
    static inline const void main() {
        scanf("%u", &n);
        for (register uint i(0); i < n; ++i) scanf("%u", &a[i]);
        for (register uint i(0); i < n; ++i) scanf("%u", &b[i]);
        discrete(a), discrete(b);
        for (register uint i(0); i < n; ++i) c[a[i]] = i;
        for (register uint i(0); i < n; ++i) b[i] = c[b[i]];
        for (register uint i(n - 1); i < n; --i)
            ans = (ans + u.query(b[i]+ 1)) % Mod,
            u.modify(b[i] + 1);
            // +1 because u[1, n] not u[0, n)
        printf("%u\n", ans);
    }
}

signed int main() { Main::main(); return 0; }