解题思路
发现如果按第一个数排序,只有第二个数成逆序对的两条路才会相交,所以直接按第一个数排序后求逆序对数量即可。
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;const int N = 1010;int n, m, k;
struct node {int x, y;
} a[N * N];
int b[N * N];int lowbit(int x) {return x & -x;
}void add(int x, int val) {for (int i = x; i <= m; i += lowbit(i)) b[i] += val;
}int sum(int x) {int res = 0;for (int i = x; i > 0; i -= lowbit(i)) res += b[i];return res;
}void Solve(int T) {memset(b, 0, sizeof b);cin >> n >> m >> k;for (int i = 1; i <= k; i ++ ) cin >> a[i].x >> a[i].y;sort(a + 1, a + k + 1, [](node a, node b){return (a.x == b.x? a.y < b.y : a.x < b.x);});int res = 0;for (int i = k; i >= 1; i -- ) {res += sum(a[i].y - 1);add(a[i].y, 1);}printf("Test case %lld: %lld\n", T, res);
}signed main() {ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);int T, cnt = 0;cin >> T;while (T -- ) Solve( ++ cnt);return 0;
}