poj 1436 && zoj 1391 Horizontally Visible Segments (Segment Tree)

ZOJ :: Problems :: Show Problem

1436 -- Horizontally Visible Segments

  用线段树记录表面能被看见的线段的编号,然后覆盖的时候同时把能看到的线段记录下来。这里要用到拆点,在两个整点之间插入一个点。

  最后O(n^2)统计三角形的个数,因为每条线段可以看见的另外的线段的条数不多,所以可以直接枚举两条边。

代码如下:

 #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set> using namespace std; const int N = ;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define root 0, 16000, 1
int cov[N << ]; void up(int rt) {
if (~cov[rt << ] && cov[rt << ] == cov[rt << | ]) cov[rt] = cov[rt << ];
else cov[rt] = -;
} void down(int rt) { if (~cov[rt]) cov[rt << ] = cov[rt << | ] = cov[rt];} void build(int L, int R, int l, int r, int rt) {
if (l >= r) {
cov[rt] = L <= l && r <= R ? : ;
return ;
}
int m = l + r >> ;
build(L, R, lson);
build(L, R, rson);
up(rt);
} set<int> edge[N >> ]; void update(int k, int L, int R, int l, int r, int rt) {
if (L <= l && r <= R && ~cov[rt]) {
if (cov[rt]) edge[k].insert(cov[rt]);
cov[rt] = k;
return ;
}
int m = l + r >> ;
down(rt);
if (L <= m) update(k, L, R, lson);
if (m < R) update(k, L, R, rson);
up(rt);
} struct Node {
int l, r, p;
} seg[N >> ]; bool cmp(Node a, Node b) { return a.p < b.p;} int main() {
// freopen("in", "r", stdin);
int T, n;
scanf("%d", &T);
while (T-- && ~scanf("%d", &n)) {
for (int i = ; i <= n; i++) {
scanf("%d%d%d", &seg[i].l, &seg[i].r, &seg[i].p);
seg[i].l <<= , seg[i].r <<= ;
}
sort(seg + , seg + n + , cmp);
edge[].clear();
build(seg[].l, seg[].r, root);
for (int i = ; i <= n; i++) {
edge[i].clear();
update(i, seg[i].l, seg[i].r, root);
}
set<int>::iterator si, sj;
int ans = ;
for (int i = ; i <= n; i++) {
// cout << i << " : ";
// for (si = edge[i].begin(); si != edge[i].end(); si++) cout << *si << ' ';
// cout << endl;
for (si = edge[i].begin(); si != edge[i].end(); si++) {
int t = *si;
for (sj = edge[i].begin(); sj != edge[i].end(); sj++) {
ans += edge[t].find(*sj) != edge[t].end();
}
}
}
printf("%d\n", ans);
}
return ;
}

——written by Lyon

上一篇:JAVA 基础知识学习笔记 名称解释


下一篇:[原创] WINDOWS 7 精简教程之驱动精简 可用于64和32