精灵魔法

题目描述

  • Tristan 解决了英灵殿的守卫安排后,便到达了静谧的精灵领地—— Alfheim 。由于 Midgard 处在 Alfheim 和冥界 Hel 的中间,精灵族领地尚未受到冥界恶灵的侵入。族长 Galanodel 为了帮助米德加尔特抵御外敌,对邪恶亡灵军团使用了高等魔法,从而使得亡灵军团每个士兵的行进速度变得不一致,从而打乱冥王 Hel 安排的最佳阵型。
  • 由于这个军团离 Midgard 还很远,因此在抵达 Midgard 之前,对于 A,B 两个亡灵,若 A 的初始位置在 B 后面且 A 的速度比 B 快, A 就会冲到 B 的前面去。现在 Galanodel 想知道,会有多少对亡灵之间出现反超现象?

输入格式

  • 第一行一个整数 n ,表示排成一队的邪恶亡灵军团有多少人。
  • 第二行 n 个整数 a[i] ,表示邪恶亡灵们在数轴上的初始坐标。数据保证这些坐标全部不同。亡灵军团向数轴正方向前进。
  • 第三行 n 个整数 v[i] ,表示邪恶亡灵们的行进速度。

输出格式

一行一个正整数(K),表示「反超」的个数。

样例

样例输入

3
1 2 3
2 1 3

样例输出

1

code

/*
3
1 2 3
2 1 3
*/
/*
1
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
#define int long long
struct edge {
    int x, v;
} a[maxn];

int lowbit(int x) { return x & (-x); }
int n, b[maxn], tot[maxn];
void add(int x) {
    while (x <= n) tot[x]++, x += lowbit(x);
}
int query(int x) {
    int cnt = 0;
    while (x) cnt += tot[x], x -= lowbit(x);
    return cnt;
}
bool cmp(edge a, edge b) { return a.x < b.x; }
signed main() {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i].x;
    for (int i = 1; i <= n; i++) cin >> a[i].v, b[i] = a[i].v;
    stable_sort(a + 1, a + n + 1, cmp);
    stable_sort(b + 1, b + n + 1);
    for (int i = 1; i <= n; i++) a[i].v = lower_bound(b + 1, b + n + 1, a[i].v) - b;
    int cnt = 0;
    for (int i = n; i >= 1; i--) cnt += query(a[i].v - 1), add(a[i].v);
    return cout << cnt << endl, 0;
}
原文地址:https://www.cnblogs.com/hellohhy/p/13269011.html