HDU 1556 Color the ball [线段树]
来源:互联网 发布:微软授权淘宝经销商 编辑:程序博客网 时间:2024/05/17 04:21
Description
1..N
给出N个更新a, b
[a, b]区间内所有数 + 1
最后问
1..N是多少
Algorithm
线段树
写了一个线段树的类
然后线段树的核心数组不能放在类里面,不然就爆炸了
于是放在线段树外 过了
此外JAVA TLE
写了C++的
这个线段树是一个完全二叉树
用数组实现 (a数组)
a中的每一个元素记录这个区间[l, r] 加的次数x
0号节点 记录 0 ~ n - 1加的次数
1号节点 记录 0 ~ n / 2加的次数
2号节点 记录 n / 2 + 1 ~ n - 1加的次数
。。。
每次进来一对区间[l, r]
就在里面找 没必要每一次都加 只需要 在相应的位置加上就好
最后再全部加一遍
这就是快的地方!
线段树是一个很抽象的数据结构,不同的题目要要用不同的方法
Code
#include <iostream>#include <climits>#include <cstring>#include <cstdio>using namespace std;const int MAX_N = 100000 + 9;struct Node{ int l; int r; int x;};Node a[MAX_N * 10];struct SegmentTree{ static const int INF = INT_MAX / 2; int n; int total; int ans[MAX_N]; void init(int i, int l, int r) { a[i].l = l; a[i].r = r; a[i].x = 0; if (l != r) { int mid = (l + r) / 2; init(2 * i + 1, l, mid); init(2 * i + 2, mid + 1, r); } } void update(int i, int l, int r) { if (a[i].l == l && a[i].r == r) { a[i].x++; return; } int mid = (a[i].l + a[i].r) / 2; if (r <= mid) { update(2 * i + 1, l, r); return; } if (l > mid) { update(2 * i + 2, l, r); return; } update(2 * i + 1, l, mid); update(2 * i + 2, mid + 1, r); } void add(int x) { for (int i = a[x].l; i <= a[x].r; i++) { ans[i] += a[x].x; } if (a[x].l == a[x].r) return; add(2 * x + 1); add(2 * x + 2); } SegmentTree(int nn) { total = nn;// memest(a, 0, sizeof(a)); memset(ans, 0, sizeof(ans)); init(0, 0, total - 1); } void print() { printf("%d", ans[0]); for (int i = 1; i < total; i++) { printf(" %d", ans[i]); } putchar('\n'); }};int main(){ int n; for (;;) { scanf("%d", &n); if (n == 0) break; SegmentTree st = SegmentTree(n); for (int i = 0; i < n; i++) { int x, y; scanf("%d%d", &x, &y); x--; y--; st.update(0, x, y); } st.add(0); st.print(); }}
0 0
- HDU 1556 Color the ball 线段树
- HDU 1556 Color the ball (线段树)
- HDU 1556 Color the ball 线段树
- hdu 1556 Color the ball(线段树)
- hdu 1556 Color the ball 线段树
- HDU 1556 Color the ball 线段树
- HDU 1556 Color the ball [线段树]
- HDU 1556 Color the ball (线段树)
- hdu - 1556 (Color the ball 线段树)
- hdu 1566 Color the ball---线段树
- HDU 1199 Color the Ball (线段树)
- hdu 1556 Color the ball(线段树的另一种应用)
- hdu 1556 Color the ball(线段树+懒惰标记)
- hdu 1556 Color the ball(线段树)
- hdu 题目1556 Color the ball(线段树)
- HDU--1556 -- Color the ball [树状数组] [线段树]
- HDU -1556 Color the ball -线段树-成段更新
- HDU--杭电--1556--Color the ball--线段树
- Android项目重构之路:界面篇
- ajax
- HDU1054(二分图)
- Java通过jdbc远程操控MySQL数据库
- 正则表达式入门
- HDU 1556 Color the ball [线段树]
- mysql主从复制
- Codeforces 27B - Tournament (dfs)
- View Controller
- poj之旅——3669
- 超详细JSON解析步骤
- jQuery事件对象
- 派生类的构造函数和析构函数和多继承中的二义性与虚函数
- 数组名取地址带来的问题