思路:线段树,区间更新
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 #include<cmath> 5 #include<set> 6 #include<algorithm> 7 #include<cstdio> 8 #include<map> 9 #include<cstring> 10 #include<list> 11 12 #define MAXSIZE 100010 13 14 using namespace std; 15 16 int tree[MAXSIZE*4]; 17 int lz[MAXSIZE*4]; 18 int N; 19 int cnt = 0; // 控制输出的打印格式 20 21 22 void init() 23 { 24 memset(tree, 0, sizeof(tree)); 25 memset(lz, 0, sizeof(lz)); 26 } 27 28 29 void build(int node, int l, int r) 30 { 31 if(l == r) 32 { 33 tree[node] = 0; 34 return; 35 } 36 int mid = (l+r)/2; 37 build(node*2, l, mid); 38 build(node*2+1, mid+1, r); 39 40 tree[node] = tree[node*2] + tree[node*2+1]; 41 } 42 43 44 void push_down(int node, int l, int r) 45 { 46 if(lz[node]) 47 { 48 int mid = (l+r)/2; 49 lz[node*2] += lz[node]; 50 lz[node*2+1] += lz[node]; 51 tree[node*2] += (mid-l+1)*lz[node]; 52 tree[node*2+1] += (r-mid)*lz[node]; 53 lz[node] = 0; 54 } 55 } 56 57 58 void update_range(int node, int l, int r, int L, int R, int add) 59 { 60 if(l <= L && r >= R) 61 { 62 lz[node] += add; 63 tree[node] += (R-L+1)*add; 64 return; 65 } 66 67 push_down(node, L, R); 68 int mid = (L+R)/2; 69 if(mid >= l) 70 update_range(node*2, l, r, L, mid, add); 71 if(mid < r) 72 update_range(node*2+1, l, r, mid+1, R, add); 73 74 tree[node] = tree[node*2] + tree[node*2+1]; 75 } 76 77 78 void print(int node, int l, int r) 79 { 80 if(l == r) 81 { 82 cnt++; 83 printf("%d", tree[node]); 84 if(cnt != N) 85 printf(" "); 86 else 87 printf(" "); 88 return; 89 } 90 push_down(node, l, r); // 此处一定要记得push_down ! 91 int mid = (l+r)/2; 92 print(node*2, l, mid); 93 print(node*2+1, mid+1, r); 94 95 } 96 97 int main() 98 { 99 100 while(scanf("%d", &N) != EOF) 101 { 102 if(N == 0) 103 break; 104 init(); 105 build(1, 1, N); 106 for(int i = 0; i < N; ++i) 107 { 108 int a, b; 109 scanf("%d%d", &a, &b); 110 update_range(1, a, b, 1, N, 1); 111 } 112 cnt = 0; 113 print(1, 1, N); 114 } 115 116 return 0; 117 }