区间相交问题

区间相交问题

时间: 1ms        内存:64M

描述:

给定x 轴上n个闭区间。去掉尽可能少的闭区间,使剩下的闭区间都不相交。

给定n个闭区间,计算去掉的最少闭区间数。

输入:

输入数据的第一行是正整数n(n≤100),表示闭区间数。接下来的n行中,每行有2 个整数,分别表示闭区间的2个数端点。

输出:

将计算出的去掉的最少闭区间数输出

示例输入:

3
10 20
10 15
20 15

示例输出:

2

提示:

参考答案(内存最优[752]):

#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);
}

参考答案(时间最优[0]):

#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);
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注