首页 > 代码库 > codeforces 652D - Nested Segments
codeforces 652D - Nested Segments
You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
Input
The first line contains a single integer n (1?≤?n?≤?2·105) — the number of segments on a line.
Each of the next n lines contains two integers li and ri (?-?10e9?≤?li?<?ri?≤?10e9) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide.
Output
Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment.
题意:给你n个区间问你每个区间包含了几个小区间,这些区间没有相交。
求区间个数与线段树求逆序对方法差不多,先按右区间排序,再利用求逆序数的思想。还有由于区间数比较大但区间的个数少,要离散化一下。
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #include <map> 5 using namespace std; 6 const int M = 2e5 + 10; 7 struct ss { 8 int x , y , num; 9 }s[M]; 10 int m[M << 1] , ans[M << 1]; 11 bool cmp(ss a , ss b) { 12 return a.y < b.y; 13 } 14 bool cmp1(ss a , ss b) { 15 return a.num < b.num; 16 } 17 struct TnT { 18 int l , r , sum; 19 }T1[M << 4] , T2[M << 4]; 20 void build(TnT T[] , int l , int r , int p) { 21 int mid = (l + r) >> 1; 22 T[p].l = l , T[p].r = r , T[p].sum = 0; 23 if(T[p].l == T[p].r) { 24 return ; 25 } 26 build(T , l , mid , p << 1); 27 build(T , mid + 1 , r , (p << 1) | 1); 28 } 29 void updata(TnT T[] , int pos , int p) { 30 int mid =(T[p].l + T[p].r) >> 1; 31 if(T[p].l == T[p].r && T[p].l == pos) { 32 T[p].sum++; 33 return ; 34 } 35 if(mid >= pos) { 36 updata(T , pos , p << 1); 37 } 38 else { 39 updata(T , pos , (p << 1) | 1); 40 } 41 T[p].sum = T[p << 1].sum + T[(p << 1) | 1].sum; 42 } 43 int query(TnT T[] , int l , int r , int p) { 44 int mid = (T[p].l + T[p].r) >> 1; 45 if(T[p].l == l && T[p].r == r) { 46 return T[p].sum; 47 } 48 if(mid < l) { 49 return query(T , l , r , (p << 1) | 1); 50 } 51 else if(mid >= r) { 52 return query(T , l , r , p << 1); 53 } 54 else { 55 return query(T , l , mid , p << 1) + query(T , mid + 1 , r , (p << 1) | 1); 56 } 57 } 58 int main() 59 { 60 int n; 61 while(cin >> n) { 62 int MAX = 0; 63 map<int , int> mp; 64 int cnt = 0; 65 memset(s , 0 , sizeof(s)); 66 for(int i = 0 ; i < n ; i++) { 67 cin >> s[i].x >> s[i].y; 68 m[++cnt] = s[i].x; 69 m[++cnt] = s[i].y; 70 s[i].num = i; 71 MAX = max(MAX , s[i].y); 72 } 73 sort(m + 1 , m + cnt + 1); 74 for(int i = 1 ; i <= cnt ; i++) { 75 mp[m[i]] = i; 76 } 77 build(T1 , 1 , cnt , 1); 78 build(T2 , 1 , cnt , 1); 79 sort(s , s + n , cmp); 80 for(int i = 0 ; i < n ; i++) { 81 updata(T1 , mp[s[i].y] , 1); 82 updata(T2 , mp[s[i].x] , 1); 83 ans[s[i].num] = min(query(T1 , 1 , mp[s[i].y] - 1 , 1) , query(T2 , mp[s[i].x] + 1 , cnt , 1)); 84 } 85 for(int i = 0 ; i < n ; i++) { 86 cout << ans[i] << endl; 87 } 88 } 89 return 0; 90 }
codeforces 652D - Nested Segments
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。