当前位置: 代码迷 >> 综合 >> POJ 1436 Horizontally Visible Segments 线段树
  详细解决方案

POJ 1436 Horizontally Visible Segments 线段树

热度:86   发布时间:2024-01-13 18:09:46.0

题目大意是,给出了很多条平行于y轴的线段,然后定义,两条线段能互相‘看见’的条件是,两条线段能由一条水平线连接,且这条水平线不能跟其他的所有线段有交点。

而题目要求的是,3个线段能互相看见,这个条件下有多少组不同的。

然后就能明显的感觉到是区间覆盖问题了。但是有一个细节问题,就是中间的水平线不一定经过整点,所以即使这个区间的所有点都被覆盖,也不能说其就不能穿过一条线,于是,可以将所有线段的长度扩大至2倍,这样就解决了这个问题。

然后对读入的数据,先按x坐标进行排序,然后从左到右,一次对每条线段,先进行查询,看左边能看见多少条线段,然后进行覆盖,因为很明显,如果一条线段能看见另一条线段,那么这个关系必然是相互的,所以对每条线段,只需要往左看就行了,将能看见的线段编号都存入vector中,开一个used数组进行判重

最后就是一个超级暴力的n4枚举了,貌似很不可行,实际上可以观察到平均每个线段能观察到得线段是很少的。

/*
ID: sdj22251
PROG: inflate
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAXN 8500*2
#define INF 1000000000
#define L(x) x<<1
#define R(x) x<<1|1
using namespace std;
struct node
{int left, right, mid;int cover;
}tree[4 * MAXN];
struct seg
{int s, t, x;
}p[MAXN];
vector<int>g[MAXN];
int used[MAXN];
bool cmp(seg x, seg y)
{return x.x < y.x;
}
void make_tree(int s, int e, int C)
{tree[C].left = s;tree[C].right = e;tree[C].mid = (s + e) >> 1;tree[C].cover = -1;if(s == e) return;make_tree(s, tree[C].mid, L(C));make_tree(tree[C].mid + 1, e, R(C));
}
void down(int C)
{if(tree[C].cover != -1){tree[L(C)].cover = tree[R(C)].cover = tree[C].cover;tree[C].cover = -1;}
}
void query(int s, int e, int p, int C)
{if(tree[C].cover != -1){if(used[tree[C].cover] != p){g[tree[C].cover].push_back(p);used[tree[C].cover] = p;}return;}if(tree[C].left == tree[C].right) return;down(C);if(tree[C].mid >= s) query(s, e, p, L(C));if(tree[C].mid < e) query(s, e, p, R(C));
}
void update(int s, int e, int p, int C)
{if(tree[C].left >= s && tree[C].right <= e){tree[C].cover = p; return;}down(C);if(tree[C].mid >= s) update(s, e, p, L(C));if(tree[C].mid < e) update(s, e, p, R(C));
}
int main()
{int T, n;scanf("%d", &T);while(T--){scanf("%d", &n);for(int i = 0; i <= n; i++){g[i].clear();used[i] = -1;}for(int i = 0; i < n; i++){scanf("%d%d%d", &p[i].s, &p[i].t, &p[i].x);p[i].s *= 2;p[i].t *= 2;}sort(p, p + n, cmp);make_tree(1, MAXN, 1);for(int i = 0; i < n; i++){query(p[i].s, p[i].t, i, 1);update(p[i].s, p[i].t, i, 1);}int ans = 0;for(int i = 0; i < n; i++){int t = g[i].size();for(int j = 0; j < t; j++){int tx = g[i][j];for(int k = j + 1; k < t; k++){int tt = g[tx].size();for(int l = 0; l < tt; l++)if(g[i][k] == g[tx][l]) ans++;}}}printf("%d\n", ans);}return 0;
}


  相关解决方案