# 区间相交问题

``````3
10 20
10 15
20 15``````

``2``

``````#include<stdio.h>
#include<stdlib.h>
struct closed_interval
{
int left,right;
int leng;
};
int comp(const void *p, const void *q);
main()
{
struct closed_interval *array;
int num,count,i,j,left,right;

scanf("%d",&num);

array = (struct closed_interval *)malloc(num * sizeof(struct closed_interval));
for(i = 0; i < num;i++)
{

scanf("%d",&left);
scanf("%d",&right);
if(left < right)
{
array[i].left = left;
array[i].right = right;
}
else
{
array[i].left = right;
array[i].right = left;
}
array[i].leng = 0;
for(j = 0; j < i; j++)
if(array[j].left <= array[i].left && array[j].right >= array[i].left || array[j].left <= array[i].right && array[j].right >=array[i].right)
{
array[j].leng++;
array[i].leng++;
}
}

count = 0;
qsort(array,num - 1,sizeof(struct closed_interval),comp);
while(array[0].leng)
{
for(i = 1; i <= array[0].leng; i++)
array[i].leng--;
array[0].leng = 0;
count++;
qsort(array,num - 1,sizeof(struct closed_interval),comp);
}
printf("%d",count);

}
int comp(const void *p, const void *q)
{
return (((struct closed_interval *)q)->leng - ((struct closed_interval *)p)->leng);
}
``````

``````#include<stdio.h>
#include<stdlib.h>
struct closed_interval
{
int left,right;
int leng;
};
int comp(const void *p, const void *q);
main()
{
struct closed_interval *array;
int num,count,i,j,left,right;

scanf("%d",&num);

array = (struct closed_interval *)malloc(num * sizeof(struct closed_interval));
for(i = 0; i < num;i++)
{

scanf("%d",&left);
scanf("%d",&right);
if(left < right)
{
array[i].left = left;
array[i].right = right;
}
else
{
array[i].left = right;
array[i].right = left;
}
array[i].leng = 0;
for(j = 0; j < i; j++)
if(array[j].left <= array[i].left && array[j].right >= array[i].left || array[j].left <= array[i].right && array[j].right >=array[i].right)
{
array[j].leng++;
array[i].leng++;
}
}

count = 0;
qsort(array,num - 1,sizeof(struct closed_interval),comp);
while(array[0].leng)
{
for(i = 1; i <= array[0].leng; i++)
array[i].leng--;
array[0].leng = 0;
count++;
qsort(array,num - 1,sizeof(struct closed_interval),comp);
}
printf("%d",count);

}
int comp(const void *p, const void *q)
{
return (((struct closed_interval *)q)->leng - ((struct closed_interval *)p)->leng);
}
``````