1. 程式人生 > >區間重合判斷(C語言實現)

區間重合判斷(C語言實現)

問題描述:

給定一個源區間[x,y](y>=x)和N個無序的目標區間[x1,y1],[x2,y2],[x3,y3],......[xN,yN],判斷源區間[x,y]是不是在目標區間內?

例如給定源區間[1,6]和一組無序的目標區間[2,3],[1,2],[2,9],[3,4],即可認為區間[1,6]在區間[2,3],[1,2],[2,9],[3,4]內。

解決方法:

1.首先對無序的目標區間進行從小到大的排序;

2.對排好序的區間進行合併;

3.在合併後的區間中使用二分查詢來判斷給定源區間是否在被合併的這些互不相交的區間中的某一個包含。

#include <stdio.h>
#include <math.h>
#define MAX 100
struct Line
{
	int low;
	int high;
};
/*實現結構體陣列的排序*/
void quicksort(struct Line a[],int l,int h)
{
    int i,j;
    struct Line t;
    i=l;
    j=h;
    t=a[l];
    while(i<j)
    {
        while(i<j && a[j].low>t.low)
            j--;
        if(i<j)
            a[i++]=a[j];
        while(i<j && a[i].low<=t.low)
            i++;
        if(i<j)
            a[j--]=a[i];
    }
    a[i]=t;
    if(l<i-1) quicksort(a,l,i-1);
    if(h>i+1) quicksort(a,i+1,h);
}
/*對已經按照地位排好續的區間進行合併區間*/
int hebing(struct Line a[],int n)
{
	int i;
	int count=0;
	int lasthigh;
	lasthigh=a[0].high;
	for (i=1;i<n;i++)
	{
		if (lasthigh>=a[i].low)  //當區間是相交時合併
			lasthigh=a[i].high;
		else  //當區間是相離是的情況,分別儲存其中low和high
		{
			a[count++].high=lasthigh;
			a[count++].low=a[i].low;
			lasthigh=a[i].high;
		}
	}
	a[count++].high=lasthigh;  //儲存最後的一個區間的高位
	return count;
}

/*對合並以後的區間使用二分查詢的方法查詢源區間是否在目標區間上*/
void Search_souce(struct Line a[],int n,struct Line targt)
{
	int mid;
	int begin=0;
	int end=n;
	int flag=0;;
	while (begin<=end)
	{
		mid=begin+(end-begin)/2;
		if (a[mid].low<=targt.low &&a[mid].high>=targt.high)
		{
			flag=1;
			break;
		}
		else if (a[mid].low>=targt.high)
		{
			end=mid-1;
		}
		else if (a[mid].high<=targt.low)
			end=mid+1;
		else 
		{
			flag=0;
			break;
		}
	}
	if (1==flag)
		printf("yes\n");
	else 
		printf("No\n");
}
int main()
{
	struct Line a[]={2,3,1,2,4,9,3,4};
	struct Line Lines[MAX]={0};
	struct Line targt={1,6};
	int count=0;
	int i;
	quicksort(a,0,3);
	count=hebing(a,4);
	Search_souce(a,count,targt);
	for (i=0;i<count;i++)
		printf("%d %d ",a[i].low,a[i].high);
	printf("\n");
	system("pause");
	return 0;
}