ZOJ 1610 Count the Colors (线段树)
来源:互联网 发布:网络之纵横天下同人 编辑:程序博客网 时间:2024/06/07 02:38
题目链接:点击链接
题意:
在x坐标轴上画线,每条线给出起点,终点,颜色编号,要求输出画了n条线后,每种颜色的线段有多少条
思路:
注意这里是[start, end]区间内为一种颜色,可以认为不包含起点终点,和以往那些包含起点终点的题目还是有区别的。处理的方法是起点加一。
建树的时候,当颜色把当前区间完全覆盖时,我们就不往下打。
查询的时候,先push down,如果当前区间在目标区间内时,遇到标记直接统计,没遇到标记就往下,直到当前区间缩为一个点。
如何统计每种颜色的线段的数目呢?线段树查询是先左后右的,所以我们先记录某种颜色线段出现的起点和终点,下一次遇到相同颜色的时候,我们需要判断这两条相同颜色的线段是否是相邻的,不相邻那么这个颜色的线段数就加1。
简而言之就是,利用点对应的区间进行相互判断,进行合并。
代码
#include <iostream>#include <cstring>#include <cstdio>#include <vector>#include <map>using namespace std;const int maxn = 8000 + 10;struct Node{ int le, ri, val; Node(){} Node(int le, int ri):le(le), ri(ri){}}A[maxn];int color[maxn<<2];int vis[maxn]; vector<Node> v[maxn];void init(){ memset(color, -1, sizeof(color)); memset(vis, 0, sizeof(vis)); for(int i=0; i<maxn; ++i) v[i].clear();}void pushdown(int rt){ if(color[rt]!=-1){ color[rt<<1] = color[rt<<1|1] = color[rt]; color[rt] = -1; } }void Set(int rt, int a, int b, int l, int r, int x){ if(a<=l && r<=b){ color[rt] = x; } else{ pushdown(rt); int mid = (l+r)>>1; if(a<=mid) Set(rt<<1, a, b, l, mid, x); if(mid<b) Set(rt<<1|1, a, b, mid+1, r, x); }}void query(int rt, int l, int r){ if(color[rt]==-1){ if(l==r) return; int mid = (l+r)>>1; query(rt<<1, l, mid); query(rt<<1|1, mid+1, r); } else{ if(v[color[rt]].size() == 0){ ++vis[color[rt]]; v[color[rt]].push_back(Node(l, r)); } else{ int tl = v[color[rt]][0].le; int tr = v[color[rt]][0].ri; if(tr+1 < l){ ++vis[color[rt]]; } v[color[rt]][0].le = l; v[color[rt]][0].ri = r; } }}int main(){ int n, cnt; while(scanf("%d", &n)!=EOF){ cnt = -1; init(); for(int i=0; i<n; ++i){ scanf("%d%d%d", &A[i].le, &A[i].ri, &A[i].val); cnt = max(cnt, A[i].ri); } for(int i=0; i<n; ++i){ if(A[i].ri == A[i].le) continue; Set(1, A[i].le+1, A[i].ri, 1, cnt, A[i].val); } query(1, 1, cnt); for(int i=0; i<maxn; ++i){ if(vis[i]!=0){ printf("%d %d\n", i, vis[i]); } } printf("\n"); } return 0;}
阅读全文
0 0
- ZOJ 1610Count the Colors//线段树
- zoj 1610 Count the Colors【线段树】
- zoj 1610 Count the Colors[线段树]
- 【线段树】Count the Colors (zoj 1610)
- zoj 1610 Count the Colors(线段树)
- zoj 1610 Count the Colors 线段树
- ZOJ - 1610 Count the Colors(线段树)
- ZOJ 1610 Count the Colors【线段树】
- ZOJ----1610-Count the Colors(线段树)
- zoj 1610 Count the Colors(线段树)
- ZOJ 1610 Count the Colors【线段树】
- zoj 1610 Count the Colors(线段树延迟更新)
- ZOJ 题目1610 Count the Colors(线段树)
- zoj - 1610 - Count the Colors(线段树)
- zoj 1610 Count the Colors(线段树染色)
- ZOJ 1610 Count the Colors(线段树区间更新)
- ZOJ 1610 Count the Colors (线段树区间染色)
- zoj 1610 Count the Colors(线段树 区间更新)
- Palindromic Numbers LightOJ
- Lasso回归的坐标下降法推导
- HDMI之TMDS通道
- Linux 之vi应用
- POJ 3253 Fence Repair(哈夫曼树+优先队列)
- ZOJ 1610 Count the Colors (线段树)
- Makefile遍历所有头文件以及源文件
- POJ1017 Packets (贪心)
- POJ
- 单点登录详解(二)--CAS实现单点登录
- ajax请求错误返回status 0和错误error的问题
- tarjan 算法求强连通分量
- HDU 6136 Death Podracing 优先队列 + 循环链表(模拟)
- 最优化算法(四)