http://acm.hdu.edu.cn/showproblem.php?pid=5124
2 5 1 2 2 2 2 4 3 4 5 1000 5 1 1 2 2 3 3 4 4 5 5
3 1
我们可以将一条线段 [xi,yi] 分为两个端点 xi 和 (yi)+1 ,在 xi 时该点会新加入一条线段,同样的,在 (yi)+1 时该点会减少一条线段,因此对于2n个端点进行排序,令 xi 为价值1, yi 为价值-1,问题转化成了最大区间和,因为1一定在-1之前,因此问题变成最大前缀和,我们寻找最大值就是答案
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <cmath> #include <cstdlib> #include <limits> #include <queue> #include <stack> #include <vector> #include <map> using namespace std; #define N 550000 #define INF 0x3f3f3f3f #define PI acos (-1.0) #define EPS 1e-8 #define met(a, b) memset (a, b, sizeof (a)) typedef long long LL; struct node { int x, num; }p[N]; bool cmp (node a, node b) { return a.x < b.x; } int main () { int t; scanf ("%d", &t); while (t--) { int n, k = 0, x, y; scanf ("%d", &n); for (int i=1; i<=n; i++) { scanf ("%d %d", &x, &y); p[k].x = x, p[k++].num = 1; p[k].x = y+1, p[k++].num = -1; } sort (p, p+k, cmp); int cnt = 0, ans = 0; for (int i=0; i<k;) { int j = i; while (p[i].x == p[j].x && j<k) cnt += p[j++].num; ans = max (ans, cnt); i = j; } printf ("%d\n", ans); } return 0; }