In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.
Your program should handle the queries of the following two types:
- "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.
- "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?
Answer all the queries. Note, that initially you have an empty set of intervals.
The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.
It's guaranteed that all queries are correct.
For each query of the second type print "YES" or "NO" on a separate line depending on the answer.
5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2
NO YES
这个格式真的是让我蒙了····不知道怎么整了,就这么写吧,今天学弟们做的题····当时想用并查集写了,然后就没有然后了,DFS还是很好写的,看能不能搜到,如果搜到,vis数组标记,如果标记了,就YES,否则就NO
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<set>
#include<algorithm>
#include<cmath>
#define ll __int64
#define MAX 1000009
using namespace std;
struct node
{
int x,y;
}p[MAX];
int k;
int vis[MAX];
void dfs(int ss,int k)
{
vis[ss] = 1;
for(int i = 0;i<k;i++)
{
if(((p[i].x<p[ss].x&&p[ss].x<p[i].y)||(p[i].x<p[ss].y&&p[ss].y<p[i].y))&&!vis[i])
{
dfs(i,k);
}
}
}
int main()
{
int n,m;
int a,b;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>m>>a>>b;
if(m==1)
{
p[k].x = a;
p[k].y = b;
k++;
}
else
{
--a;
--b;
memset(vis,0,sizeof(vis));
dfs(a,k);
if(!vis[b])
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
}
return 0;
}
本文介绍了一种基于深度优先搜索(DFS)的算法实现,用于解决区间间的可达性问题。通过递归地遍历所有可能的路径来判断两个区间是否相连,并使用vis数组记录已访问过的区间,最终给出查询结果。
1675

被折叠的 条评论
为什么被折叠?



