给定 nn 个区间 [l,r],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
#include <iostream> #include <algorithm> #include <climits> using namespace std; const int N = 100010; int n; struct node { int l, r; }e[N]; bool cmp (node x, node y) { if (x.l==y.l) return x.r < y.r; return x.l < y.l; } int main() { scanf ("%d", &n); for (int i=0; i<n; i++) scanf ("%d%d", &e[i].l, &e[i].r); sort (e, e+n, cmp); int pos = INT_MIN, ans = 0; for (int i = 0; i < n; i++) { if (e[i].l > pos) { ans++; pos = e[i].r; } else { pos = max (pos, e[i].r); } } cout << ans << endl; return 0; }
标签:node,int,合并,pos,区间,include From: https://www.cnblogs.com/leetothemoon/p/16939809.html