嘟嘟嘟
首先可以想到,最小距离一定是a中第 i 大的和b中第 i 大的在同一行。
然后先把a,b分别离散化,然后开一个标记数组,map[i]记录a中第 i 小的数在哪一个位置出现,然后对b数组处理一遍。
题中说交换次数,自然想到逆序对,于是我们对新的b数组求一遍逆序对就行了。
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<cstdlib> 7 #include<cctype> 8 #include<stack> 9 #include<queue> 10 #include<vector> 11 using namespace std; 12 #define enter puts("") 13 #define space putchar(' ') 14 #define Mem(a, x) memset(a, x, sizeof(a)) 15 #define rg register 16 typedef long long ll; 17 typedef double db; 18 const int INF = 0x3f3f3f3f; 19 const db eps = 1e-8; 20 const ll mod = 99999997; 21 const int maxn = 1e5 + 5; 22 inline ll read() 23 { 24 ll ans = 0; 25 char ch = getchar(), las = ' '; 26 while(!isdigit(ch)) las = ch, ch = getchar(); 27 while(isdigit(ch)) ans = (ans << 3) + (ans << 1) + ch - '0', ch = getchar(); 28 if(las == '-') ans = -ans; 29 return ans; 30 } 31 inline void write(ll x) 32 { 33 if(x < 0) putchar('-'), x = -x; 34 if(x >= 10) write(x / 10); 35 putchar(x % 10 + '0'); 36 } 37 38 int n; 39 int a[maxn], b[maxn]; 40 ll ta[maxn], tb[maxn], f[maxn]; 41 ll c[maxn], sum = 0; 42 43 int lowbit(int x) 44 { 45 return x & -x; 46 } 47 void add(int pos) 48 { 49 while(pos <= n) 50 { 51 c[pos]++; 52 pos += lowbit(pos); 53 } 54 } 55 ll query(int pos) 56 { 57 ll ret = 0; 58 while(pos) 59 { 60 ret += c[pos]; 61 ret %= mod; 62 pos -= lowbit(pos); 63 } 64 return ret; 65 } 66 67 int main() 68 { 69 n = read(); 70 for(int i = 1; i <= n; ++i) a[i] = read(), ta[i] = a[i]; 71 for(int i = 1; i <= n; ++i) b[i] = read(), tb[i] = b[i]; 72 sort(ta + 1, ta + n + 1); 73 sort(tb + 1, tb + n + 1); 74 for(int i = 1; i <= n; ++i) a[i] = lower_bound(ta + 1, ta + n + 1, a[i]) - ta; 75 for(int i = 1; i <= n; ++i) b[i] = lower_bound(tb + 1, tb + n + 1, b[i]) - tb; 76 for(int i = 1; i <= n; ++i) f[a[i]] = i; 77 for(int i = 1; i <= n; ++i) b[i] = f[b[i]]; 78 for(int i = n; i; --i) 79 { 80 sum += query(b[i]); sum %= mod; 81 add(b[i]); 82 } 83 write(sum); enter; 84 return 0; 85 }