您的位置:首页 > 其它

求区间最大值---找出下面“输入数据及格式”中所描述的输入数据文件中最大重叠区间的大小

2014-06-19 17:34 351 查看
题目描述:请编写程序,找出下面“输入数据及格式”中所描述的输入数据文件中最大重叠区间的大小。

对一个正整数 n ,如果n在数据文件中某行的两个正整数(假设为A和B)之间,即A<=n<=B或A>=n>=B ,则 n 属于该行;

如果 n 同时属于行i和j ,则i和j有重叠区间;重叠区间的大小是同时属于行i和j的整数个数。

例如,行(10 20)和(12 25)的重叠区间为 [12 20] ,其大小为9,行(20 10)和( 20 30 )的重叠区间大小为 1 。

实现起来不难
#include<stdio.h>

void swap( int *a, int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}

void find(int first_one[], int second_one[])
{

//先使它们变成正规的区间表达式
if(first_one[1]<first_one[0])
swap(first_one,first_one+1);
if(second_one[1]<second_one[0])
swap(second_one,second_one+1);

//如果其中一个区间的最大值小于另一个区间的最小值,显然是没有交集的
if(first_one[0]>second_one[1] || second_one[0]>first_one[1])
{
printf("0\n");
}

else
{
//寻找两个区间右边值较小,左值较大的数
if(first_one[1]<second_one[1])
{
if(first_one[0]>second_one[0])
{
printf("%d \n", first_one[1]-first_one[0]+1);
}
else
{
printf("%d \n",first_one[1]-second_one[0]+1);
}
}
else
{
if(first_one[0]>second_one[0])
{
printf("%d \n", second_one[1]-first_one[0]+1);
}
else
{
printf("%d \n",second_one[1]-second_one[0]+1);
}
}
}
}

int main()
{
int first_one[2];
int second_one[2];
scanf("%d%d",&first_one[0],&first_one[1]);
scanf("%d%d",&second_one[0],&second_one[1]);

find( first_one, second_one);
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐