The classic topic of reverse order. Exam time do not know how to write ugly, all WA, just take me to review the reverse order.
The match sequence is assigned a rank from small to large, and when the grade of a is at the same level as the corresponding B, the answer is the least, and as for why, I do not prove it. The hierarchy here is, in fact, discretization.
The rank of a from small to large, and then the b corresponding to the rank of a, the order appears in the rank sequence of B pairs, is the number of exchanges we require, because each exchange, can only make a group of reverse order to become orderly.
Note that the search for reverse order is to time out, only 70 points, so the tree-like array can be used.
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define MAXN 100005#define mod 99999997using namespace std;struct t{int num; int POS;} A[maxn],b[maxn];int tree[maxn];int c[maxn];int n;bool cmp1 (T x,t y) {return x.num < Y.num;} int lowbit (int x) {return x&-x;} void Update (int pos) {for (int i = pos; I <= n; i + = Lowbit (i)) tree[i]++;} int getsum (int pos) {int res = 0; for (int i = pos; I >= 1; I-= Lowbit (i)) res = (Res+tree[i])%mod; return res;} int main () {scanf ("%d", &n); for (int i = 1; I <= n; i++) {scanf ("%d", &a[i].num); a[i].pos = i;} for (int i = 1; I <= n; i++) {scanf ("%d", &b[i].num); b[i].pos = i;} Sort (A+1,A+N+1,CMP1); Sort (B+1,B+N+1,CMP1); for (int i = 1; I <= n; i++) C[a[i].pos] = B[i].pos; int ans = 0; for (int i = 1; I <= n; i++) {update (c[i]); Ans = (ans + i-getsum (c[i]))%mod; } printf ("%d\n", ans); Return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
NOIP2013 Match Line