跳到正文

题解

[Solution] P1966 #NOIP2013 TG

KaguyaH约 5 分钟
原文
文章信息与版本

文章信息

发布
2019年10月5日
收录
2025年12月12日
更新
2026年11月12日
篇幅
约 5 分钟
获赞
14
题目
P1966

版本

  1. v1当前

P1966.


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


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

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

1⩽n⩽1051 \leqslant n \leqslant 10^5,0⩽ai,bi<2310 \leqslant a_i, b_i < 2^{31},∀ 1⩽i<j⩽n, ai≠aj∧bi≠bj\forall\ 1 \leqslant i < j \leqslant n,\,a_i \ne a_j \land b_i \ne b_j。


∑(ai−bi)2=∑(ai2+bi2−2aibi),\sum(a_i - b_i)^2 = \sum(a_i^2 + b_i^2 - 2 a_i b_i),

上式取最小值等价于 ∑aibi\sum a_i b_i 取最大值。


若 ai⩽aja_i \leqslant a_j,bp⩽bqb_p \leqslant b_q,

则

(aibp+ajbq)−(aibq+ajbp)=(ai−aj)(bp−bq)⩾0,(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,

故 aibp+ajbq⩾aibq+ajbp.a_i b_p + a_j b_q \geqslant a_i b_q + a_j b_p.

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


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

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

设 cai=ic_{a_i} = i,则 bib_i 应该最终移到 bb 中位置 cbic_{b_i}。

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

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

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


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

C++
# 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; }
原文
存档评论3 条抓取于