[Solution] P1966 #NOIP2013 TG
P1966.
Changelog:简化题解,修复了
给定两个序列
求:要使
综上,应使
比较直观地,要使操作次数最小,有一种可行方案是:只对
因为是相对顺序,所以我们可以先进行离散化,问题变为使
设
于是我们再进行一波处理:
处理后,问题变为使
此时的操作次数即为
代码用树状数组求逆序对。
# 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; }