区间合并的应用:格子染色(2019美团面试题)

上题先:

区间合并的应用:格子染色(2019美团面试题)_第1张图片

其实我一开始是用的离散化再加上二维前缀和做的,我将每个点的的x,y值都进行离散化,虽然避免了开一个2e9*2e9的数组,但是离散化后的a数组也需要2e5*2e5理所当然的MLE了,虽然后面想想我这个离散化后从根本上就是错误的,因为离散化后的数组并不能将原本线段的重合给还原出来。后面看了题解才发现,要用到二维的区间合并,然后再判重。与一维的区间合并不同的就是要在每个区间的存储时加上其行号/列号。一维前缀和模板详见我的博客:区间合并

以下是具体ac代码:时间复杂度是o(n**2),n是1e4

#include 
#include 
#include 

using namespace std;

typedef long long ll;

struct node
{
	int k,l,r;
	bool operator <(const node& w) const
	{
		if(k!=w.k) return k cols,rows;

void merge(vector &segs)
{
	vector res;
	
	int st=-2e9,ed=-2e9,k=-2e9;
	for(auto seg:segs)
	{
		if(seg.k==k)
		{
			if(ed>n;
	while(n--)
	{
		int x1,y1,x2,y2;
		cin>>x1>>y1>>x2>>y2;		
		
		if(x1==x2) rows.push_back({x1,min(y1,y2),max(y1,y2)});
		else cols.push_back({y1,min(x1,x2),max(x1,x2)});
	}
	
	sort(cols.begin(),cols.end());
	sort(rows.begin(),rows.end());
	merge(rows);
	merge(cols);
	
	for(auto col:cols)
		for(auto row:rows)
			if(row.k>=col.l&&row.k<=col.r&&col.k>=row.l&&col.k<=row.r) cnt--;
	
	cout<

 

你可能感兴趣的:(算法)