poj1201 Intervals

本文介绍了一种结合贪心策略与线段树数据结构的算法实现,通过具体代码示例展示了如何解决特定类型的问题。该算法适用于处理区间查询及更新操作,通过线段树优化了查询效率。

思路:

贪心 + 线段树。

实现:

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 const int MAXN = 50005;
 5 struct node
 6 {
 7     int l, r, c;
 8 };
 9 node a[MAXN];
10 int tree[MAXN * 4], n;
11 bool vis[MAXN];
12 bool cmp(const node & a, const node & b)
13 {
14     return a.r < b.r;
15 }
16 void update(int num, int l, int r, int x, int dx)
17 {
18     if (l == r) { tree[num] += dx; return; }
19     int m = l + r >> 1;
20     if (x <= m) update(num << 1, l, m, x, dx);
21     else update(num << 1 | 1, m + 1, r, x, dx);
22     tree[num] = tree[num << 1] + tree[num << 1 | 1];
23 }
24 int query(int num, int l, int r, int x, int y)
25 {
26     if (x <= l && y >= r) return tree[num];
27     int m = l + r >> 1;
28     int ans = 0;
29     if (x <= m) ans += query(num << 1, l, m, x, y);
30     if (y >= m + 1) ans += query(num << 1 | 1, m + 1, r, x, y);
31     return ans;
32 }
33 int main()
34 {
35     ios::sync_with_stdio(false);
36     cin >> n;
37     for (int i = 0; i < n; i++) cin >> a[i].l >> a[i].r >> a[i].c;
38     sort(a, a + n, cmp);
39     int tot = 0;
40     for (int i = 0; i < n; i++)
41     {
42         int cnt = query(1, 0, 50000, a[i].l, a[i].r);
43         if (cnt < a[i].c)
44         {
45             int x = a[i].r;
46             while (cnt < a[i].c) 
47             {
48                 if (vis[x]) { x--; continue; }
49                 update(1, 0, 50000, x, 1); 
50                 vis[x--] = true;
51                 cnt++;
52                 tot++;
53             }
54         }
55     }
56     cout << tot << endl;
57     return 0;
58 }

 

转载于:https://www.cnblogs.com/wangyiming/p/8457470.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值