扫描线(线段树)

AcWing247. 亚特兰蒂斯

Code

const int N = 1e4 + 4, M = 1e6 + 6;
int n, num;

struct seg
{
	double x, y1, y2;
	int k;

	bool operator < (seg a)const
	{
		return x < a.x;
	}
}s[N * 2];

double yy[N * 2];
int fd(double x)
{
	return lower_bound(yy + 1, yy + num + 1, x) - yy;
}

struct node
{
	int l, r;
	double len;
	int cnt;
	node()
	{
		len = cnt = 0;
	}

#define tp t[p]
#define tl t[p << 1]
#define tr t[p << 1 | 1]
}t[N * 8];

void build(int p, int l, int r)
{
	tp.l = l, tp.r = r;
	if (l == r) return;//注意return
	int mid = l + r >> 1;
	build(p << 1, l, mid), build(p << 1 | 1, mid + 1, r);
}

void up(int p)
{
	if (tp.cnt) tp.len = yy[tp.r + 1] - yy[tp.l];//注意下标
	else if (tp.l == tp.r) tp.len = 0;
	else tp.len = tl.len + tr.len;
}

void change(int p, int l, int r, int k)
{
	if (l <= tp.l && tp.r <= r)
	{
		tp.cnt += k;
		up(p);
		return;
	}
	int mid = tp.l + tp.r >> 1;
	if (l <= mid) change(p << 1, l, r, k);
	if (r > mid) change(p << 1 | 1, l, r, k);
	up(p);
}

int main()
{
	IOS;
	int T = 1;
	while (cin >> n && n)
	{
		cout << "Test case #" << T++ << endl;
		for (int i = 1, j = 0; i <= n; i++)
		{
			double x, y, x1, y1;
			cin >> x >> y >> x1 >> y1;
			yy[++j] = y; yy[++j] = y1;
			s[i * 2 - 1] = { x, y, y1, 1 };
			s[i * 2] = { x1, y, y1, -1 };
		}

		sort(yy + 1, yy + n * 2 + 1);
		num = unique(yy + 1, yy + n * 2 + 1) - yy - 1;
		sort(s + 1, s + n * 2 + 1);

		build(1, 1, num);

		double ans = 0;
		change(1, fd(s[1].y1), fd(s[1].y2) - 1, s[1].k);//注意下标
		for (int i = 2; i <= n * 2; i++)
		{
			ans += t[1].len * (s[i].x - s[i - 1].x);
			change(1, fd(s[i].y1), fd(s[i].y2) - 1, s[i].k);//注意下标
		}

		cout << "Total explored area: ";
	    cout << fixed << setprecision(2) << ans << endl << endl;
	}


	return 0;
}

你可能感兴趣的:(数据结构,c++,几何学,算法)