-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path一维区间重合判断
82 lines (82 loc) · 1.9 KB
/
一维区间重合判断
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<stdio.h>
#include<stdlib.h>
#define N 100
struct Interval
{
int x,y;
};
int cmp(const void *a,const void *b)
{
return (*((struct Interval*)a)).x-(*((struct Interval*)b)).x;
}
int binarySearch(struct Interval b[],int right,struct Interval src)//二分查找最接近源区间的位置
{
int i,j,mid;
i=0;
j=right;
mid=(i+j)>>1;
while(i<j)
{
if(b[mid].x>src.x)
j=mid-1;
else if(b[mid].x<src.x)
i=mid+1;
else
return mid;
mid=(i+j)>>1;
}
return mid;
}
int intervalCoincide(struct Interval a[],int n,struct Interval src)
{
struct Interval b[N];
int i,j,pos;
i=j=0;
qsort(a,n,sizeof(struct Interval),cmp);
for(i;i<n;i++)
{
if(i!=n-1 && (a[i].y >= a[i+1].x))
{
a[i+1].x=a[i].x;
}
else
{
b[j++]=a[i];
}
}
if(src.x<b[0].x || src.y>b[j-1].y)//如果待求的区间在总区间的边界之外,则一定不再该区间内
return 0;
pos=binarySearch(b,j-1,src);
printf("pos=%d\n",pos);
if(pos<0 || pos >=j)//如果二分查找到的位置不在数组范围之内,则返回false
return 0;
if(b[pos].x<=src.x && b[pos].y>=src.y)
return 1;
else if(b[pos].x>src.x && b[pos-1].x<=src.x && b[pos-1].y>=src.y)
return 1;
return 0;
}
int main()
{
struct Interval a[N],src;
int i,j,flag,n;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%d %d",&a[i].x,&a[i].y);
}
scanf("%d %d",&src.x,&src.y);
flag=intervalCoincide(a,n,src);
if(1==flag)
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
system("pause");
return 0;
}