题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5720
官方题解:
考虑三角形三条边
a,b,c
(a≥b)
的关系
a−b<c,a+b>c
,即
c∈(a−b,a+b)
。令加入的边为
c
,枚举所有边作为
a
的情况。对于所有可行的
b
,显然与
a
相差最小的可以让
(a−b,a+b)
覆盖范围最大,所以可以贪心地选择不大于
a
的最大的
b
。于是我们可以先将边按长度排序,然后
a i
和
a i+1
建一条线段。线段并是不合法的部分。将所有线段按左端点排序,按序扫描一遍,过程中统计答案即可。时间复杂度
O(Tn logn)
。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> Pi;
LL x[100005];
Pi pr[100005];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
LL L,R;
scanf("%d%lld%lld",&n,&L,&R);
for(int i = 0; i < n; ++i) scanf("%lld",&x[i]);
sort(x,x+n);
for(int i = 0; i < n-1; ++i)
{
pr[i].first = x[i+1]-x[i];
pr[i].second = x[i+1]+x[i];
}
sort(pr,pr+n-1);
LL ans = 0;
LL mx = L;
for(int i = 0; i < n-1 && pr[i].first <= R; ++i)
{
if(pr[i].first >= mx) ans += (pr[i].first-mx+1);
mx = max(mx,pr[i].second);
}
ans += max(0LL,R+1-mx);
printf("%lld\n",ans);
}
return 0;
}