Description
Input
Output
Sample Input
1 3 4 4 1 4 2 3 3 2 3 1
Sample Output
Test case 1: 5
const int MAXN = 1002; struct Node { int a, b; } node[MAXN * MAXN]; bool cmp(Node a, Node b) { return a.a != b.a ? a.a < b.a : a.b < b.b; } sort(node + 1, node + 1 + K, cmp);
int lowbit(int x) { return -x & x; } void add(int i, int val) { while (i <= M) { c[i] += val; i += lowbit(i); } } int sum(int i) { int s = 0; while (i) { s += c[i]; i -= lowbit(i); } return s; } long long ans = 0; add(node[1].b, 1); for (int i = 2; i <= K; i++) { add(node[i].b, 1); ans += sum(M) - sum(node[i].b);//统计比node[i].b大的点个数,O(log M)时间 }
/*485ms,2760KB*/ #include<stdio.h> #include<algorithm> #include<string.h> #include<iostream> using namespace std; const int MAXN = 1002; int c[MAXN]; int N, M, K; struct Node { int a, b; } node[MAXN * MAXN]; bool cmp(Node a, Node b) { return a.a != b.a ? a.a < b.a : a.b < b.b; } int lowbit(int x) { return -x & x; } void add(int i, int val) { while (i <= M) { c[i] += val; i += lowbit(i); } } //前i项和 int sum(int i) { int s = 0; while (i) { s += c[i]; i -= lowbit(i); } return s; } int main() { int T; scanf("%d", &T); for (int iCase = 1; iCase <= T; iCase++) { scanf("%d%d%d", &N, &M, &K); for (int i = 1; i <= K; i++) { scanf("%d%d", &node[i].a, &node[i].b); } /////////////////////// sort(node + 1, node + 1 + K, cmp); //排序 memset(c, 0, sizeof(c)); long long ans = 0; add(node[1].b, 1); for (int i = 2; i <= K; i++) { add(node[i].b, 1); ans += sum(M) - sum(node[i].b);//统计比node[i].b大的点个数,O(log M)时间 } printf("Test case %d: %I64d\n", iCase, ans); } return 0; }