一开始写的代码一直TLE,我的方法是n^2的二重循环。
看完别人的解体报告后才发现了另一种更好的办法
把两个数组放在一块,然后排序,从而保证了后面的必能覆盖了前面的,把时间复杂度降到了2n
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <set>
#define LEN 100001
#define MMAX 999999
using namespace std;
typedef struct Node {
int h, w;
int type;
}Node;
Node a[LEN*2];
int cmp(Node a, Node b) {
if(a.h != b.h) return a.h < b.h;
else if(a.w != b.w) return a.w < b.w;
else return a.type > b.type;
}
int main() {
int n, t;
int i, j;
int aa, bb;
int flag, sum, tmp, index;
multiset<int> set;
scanf("%d", &n);
while(n--) {
scanf("%d", &t);
for(i = 0; i < t; i++) {
scanf("%d%d", &a[i].h, &a[i].w);
a[i].type = 0;
}
for(i = t ; i < 2*t; i++) {
scanf("%d%d", &a[i].h, &a[i].w);
a[i].type = 1;
}
sort(a, a+2*t, cmp);
// for(i = 0; i < 2*t; i++) {
// printf("%d %d %d", a[i].h, a[i].w, a[i].type);
// }
sum = 0;
set.clear();
for(i = 0; i < 2*t; i++) {
if(1 == a[i].type) {
set.insert(a[i].w);
}
else {
if(!set.empty() && *set.begin() <= a[i].w) {
multiset<int>::iterator it = set.upper_bound(a[i].w);
--it;
++sum;
set.erase(it);
}
}
}
printf("%d\n", sum);
}
return 0;
}