codeforces Educational Codeforces Round 78 (Rated for Div. 2) D - Segment Tree(set)

在这里插入图片描述
在这里插入图片描述
题意:给定n个区间,区间如果时相交关系,那么这两点就可以合并,求问合并后构成的图是不是树
思路:思路应该还是很好想的,按左端点排序枚举即可,但一开始疯狂TLE,看了测试用例才发现其实小于当前左端点的值其实可以合区,降低复杂度,就当学学会set吧。

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+1;
map<int,int>p;
int cnt=0,n,father[maxn];
set<int>st;
struct node{
	int l,r,id;
}s[maxn];
int findfather(int x)
{
	if(x==father[x]) return x;
	int i=findfather(father[x]);
	father[x]=i;
	return i;
}
int unit(int a,int b)
{
	int fa=findfather(a),fb=findfather(b);
	if(fa!=fb) 
	{
		father[fa]=fb;
		return 1;
	}
	else return 0;
}
bool cmp(const node &a,const node &b)
{
	return a.l<b.l;
}
int main()
{
	scanf("%d",&n);
	for(int i=0;i<=n;++i) father[i]=i;
	for(int i=1;i<=n;++i)  scanf("%d %d",&s[i].l,&s[i].r);
	sort(s+1,s+1+n,cmp);
	for(int i=1;i<=n;++i) p[s[i].r]=i;
	for(int i=1;i<=n;++i)
	{
		auto it=st.lower_bound(s[i].l);
		while(it!=st.end()&&*it<s[i].r)
		{
				if(unit(p[*it],i)==0) {
			printf("NO\n");return 0;
		}
		it++;cnt++;
		}
		st.insert(s[i].r);
	}
	printf("%s\n",cnt==n-1?"YES":"NO");
}
发布了39 篇原创文章 · 获赞 0 · 访问量 1086

猜你喜欢

转载自blog.csdn.net/qq_42479630/article/details/103979611