Math Problem(待改)

Math Problem

Your math teacher gave you the following problem:

There are n segments on the x-axis, [l1;r1],[l2;r2],…,[ln;rn]. The segment [l;r] includes the bounds, i.e. it is a set of such x that l≤x≤r. The length of the segment [l;r] is equal to r−l.

Two segments [a;b] and [c;d] have a common point (intersect) if there exists x that a≤x≤b and c≤x≤d. For example, [2;5] and [3;10] have a common point, but [5;6] and [1;4] don’t have.

You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments.

In other words, you need to find a segment [a;b], such that [a;b] and every [li;ri] have a common point for each i, and b−a is minimal.

Input
The first line contains integer number t (1≤t≤100) — the number of test cases in the input. Then t test cases follow.

The first line of each test case contains one integer n (1≤n≤105) — the number of segments. The following n lines contain segment descriptions: the i-th of them contains two integers li,ri (1≤li≤ri≤109).

The sum of all values n over all the test cases in the input doesn’t exceed 105.

Output
For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

Example
Input
4
3
4 5
5 9
7 7
5
11 19
4 17
16 16
3 12
14 17
1
1 10
1
1 1
Output
2
4
0
0
Note
In the first test case of the example, we can choose the segment [5;7] as the answer. It is the shortest segment that has at least one common point with all given segments.

解题思路:找所有区间左端点最大值减去区间右端点最小值,所得大于0就是答案,所得小于0为0。
(In other words, you need to find a segment [a;b], such that [a;b] and every [li;ri] have a common point for each i, and b−a is minimal.)

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
 int a[100005],b[100005];


int main()
{
    int T;
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);*/
    cin >> T;
    while(T--)
    {
        __int64 n,i,max1=0,min2=0x3f3f3f3f,ans,p,q;
        cin >> n;
        for(i=0; i<n; ++i)
        {
            scanf("%I64d%I64d",&p,&q);
            min2 = min(q,min2);
            max1 = max(p,max1);
        }
        ans = max1 - min2;
        if(ans<0)
            ans = 0;
        printf("%I64d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

葛济维的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值