线段树 ---- 染色问题

Mayor's posters

线段树染色问题

法一 : 线段树 + 离散化:

1e+7的区间范围太大了,硬刚的话就是tle或者mle,所以用到了离散化的思想

新的覆盖旧的,问最后又多少张海报会露出来,可见没法用线段树的push_up操作,我们在染色时,就是让线段树中对应一个区间的节点做一个颜色标记,然后push_bown,向下染色。

查询的时候,用hash的思想,我开了一个use数组来表示这个颜色计算过没有,我们查询的是整个区间,所以在查询的过程中,如果一个节点的颜色没有被计算进去,则ans++,这时候use[color]=1,标记这个颜色计算过,将不再重复计算。


const int N = 10010;
bool used[N<<3];
int cnt;
int info[N<<3];
struct node
{

	inline ll ls(int x){return x<<1;}
	inline ll rs(int x){return x<<1|1;}

	void push_down(int p){
		if(info[p] != -1){
			info[ls(p)] = info[rs(p)] = info[p];
			info[p] = -1;
 		}
	}

	void update(int p, int nl, int nr, int l, int r, int i) {
		if(l >= nl && r <= nr) {
			info[p] = i;
			return;
		}
		push_down(p);
		int mid = (l + r) >> 1;
		if(nl <= mid)update(ls(p), nl, nr, l, mid, i);
		if(nr > mid)update(rs(p), nl, nr, mid + 1, r, i);//
	}

	void query(int p){
		if(info[p] != -1) {
			if(!used[info[p]])cnt++;
			used[info[p]] = 1;
			return ;
		}
		push_down(p);
		query(ls(p));
		query(rs(p));
	}
}segment_tree;

int main(){
	int t, n;
	cin >> t;
	while(t--) {
		cin >> n;
		std::vector a, b;
		std::vector c;
		for (int i = 0; i < n; i++) {
			int x, y;
			cin >> x >> y;
			a.push_back(x);
			b.push_back(y);
			c.push_back(x);
			c.push_back(y);
		}		
		sort(c.begin(), c.end());
		c.erase(unique(c.begin(),c.end()),c.end());
		int m = (int)c.size();
		memset(info, -1, sizeof(info));		
		for (int i = 0; i < n; i++) {
			int l = lower_bound(c.begin(), c.end(), a[i]) - c.begin() + 1;
			int r = lower_bound(c.begin(), c.end(), b[i]) - c.begin() + 1;
			segment_tree.update(1, l, r, 1, m, i);
		}
		cnt = 0;
		memset(used, 0, sizeof(used));
		segment_tree.query(1);
		cout << cnt << "\n";
	}

	return 0;
}

 push_down 和 push_up 是反向操作,输入从后往前来,即可

const int N =10000008;
int n, t, x, y;
bool k;
bool info[N << 2];
struct node
{
	inline int ls(int x) {return x << 1;}
	inline int rs(int x) {return x << 1 | 1;}

	void build(int p, int nl, int nr, int l, int r) {
		if(info[p])return;
		if(nl <= l && r <= nr) {
			info[p] = true;
			k = 1;
			return;
		}				
		int mid = (l + r) >> 1;
		build(ls(p), nl, nr, l, mid);
		build(rs(p), nl, nr, mid + 1, r);
		info[p] = info[ls(p)] && info[rs(p)];
	}
}segment_tree;

你可能感兴趣的:(拓扑学,蓝桥杯,c++)