HDU 4325 Flowers(树状数组+离散化)

http://acm.hdu.edu.cn/showproblem.php?pid=4325

题意:
给出n个区间和m个询问,每个询问为一个x,问有多少个区间包含了x。

思路:

因为数据量比较多,所以需要离散化。区间的离散化需要注意一下,如果端点不连续的话,需要额外插点。

区间情况就用树状数组来维护。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn = 2*1e5+5;
 7 
 8 int n, m, tot;
 9 int a[maxn+1000],c[maxn];
10 
11 struct node
12 {
13     int l,r;
14 }query[maxn/2];
15 
16 int lowbit(int x)
17 {
18     return x&-x;
19 }
20 
21 int sum(int x)
22 {
23     int ret = 0;
24     while(x>0)
25     {
26         ret+=c[x];
27         x-=lowbit(x);
28     }
29     return ret;
30 }
31 
32 void add(int x, int d)
33 {
34     while(x<=maxn)
35     {
36         c[x]+=d;
37         x+=lowbit(x);
38     }
39 }
40 
41 int main()
42 {
43     //freopen("in.txt","r",stdin);
44     int T;
45     int kase = 0;
46     scanf("%d",&T);
47     while(T--)
48     {
49         tot = 0;
50         memset(c,0,sizeof(c));
51         scanf("%d%d",&n,&m);
52         for(int i=1;i<=n;i++)
53         {
54             scanf("%d%d",&query[i].l,&query[i].r);
55             a[tot++] = query[i].l;
56             a[tot++] = query[i].r;
57         }
58         a[tot++] = 0;
59         sort(a,a+tot);
60         int tmp = tot;
61         for(int i=1;i<tmp;i++)
62             if(a[i]-a[i-1]>1)  a[tot++] = a[i]-1;
63         sort(a,a+tot);
64         int num = unique(a,a+tot)-a;
65         for(int i=1;i<=n;i++)
66         {
67             int l = lower_bound(a,a+num,query[i].l)-a;
68             int r = lower_bound(a,a+num,query[i].r)-a;
69             add(l,1);
70             add(r+1,-1);
71         }
72         printf("Case #%d:
",++kase);
73         while(m--)
74         {
75             int x; scanf("%d",&x);
76             x = lower_bound(a,a+num,x)-a;
77             printf("%d
",sum(x));
78         }
79     }
80     return 0;
81 }
原文地址:https://www.cnblogs.com/zyb993963526/p/7900014.html