您的位置:首页 > 其它

hdu 5720 Wool(贪心,扫描线,区间合并)

2016-07-18 11:40 495 查看


Wool

Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)

Total Submission(s): 362    Accepted Submission(s): 103


Problem Description

At dawn, Venus sets a second task for Psyche.

She is to cross a river and fetch golden wool from violent sheep who graze on the other side.

The sheep are wild and tameless, so Psyche keeps on throwing sticks to keep them away. 

There are n sticks
on the ground, the length of the i-th
stick is ai.

If the new stick she throws forms a triangle with any two sticks on the ground, the sheep will be irritated and attack her. 

Psyche wants to throw a new stick whose length is within the interval [L,R].
Help her calculate the number of valid sticks she can throw next time.

 

Input

The first line of input contains an integer T (1≤T≤10),
which denotes the number of test cases.

For each test case, the first line of input contains single integer n,L,R (2≤n≤105,1≤L≤R≤1018).

The second line contains n integers,
the i-th
integer denotes ai (1≤ai≤1018).

 

Output

For each test case, print the number of ways to throw a stick.

 

Sample Input

2
2 1 3
1 1
4 3 10
1 1 2 4

 

Sample Output

2
5

Hint
In the first example, $ 2, 3 $ are available.

In the second example, $ 6, 7, 8, 9, 10 $ are available.

题意:地上有n根木棍,现在给一个区间[L,R],问区间内有多少个数满足从地上任取两根木棍都不能组成三角形

思路:贴一发官方题解

考虑三角形三条边a,b,ca,b,c (a
\ge b)(a≥b)的关系a
- b < c, a + b > ca−b<c,a+b>c,即c
\in (a-b,a+b)c∈(a−b,a+b)。

令加入的边为cc,枚举所有边作为aa的情况。对于所有可行的bb,显然与aa相差最小的可以让(a-b,a+b)(a−b,a+b)覆盖范围最大,所以可以贪心地选择不大于aa的最大的bb。

于是我们可以先将边按长度排序,然后a_ia​i​​和a_{i
+ 1}a​i+1​​建一条线段。线段并是不合法的部分。

将所有线段按左端点排序,按序扫描一遍,过程中统计答案即可。

时间复杂度O(Tn\ \log n)O(Tn logn)。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 100050
long long a
;
struct Inter
{
long long l,r;
}p
;
bool cmp(Inter a,Inter b)
{
return a.l<b.l;
}
int main()
{
int T,n;
long long l,r;
scanf("%d",&T);
while(T--)
{
scanf("%d %I64d %I64d",&n,&l,&r);
for(int i=1;i<=n;i++)
scanf("%I64d",&a[i]);
sort(a+1,a+1+n);
int cnt=0;
long long maxn=-1;
for(int i=2;i<=n;i++)
{
p[cnt].l=a[i]-a[i-1]+1;
p[cnt++].r=a[i]+a[i-1]-1;
maxn=max(maxn,p[cnt-1].r);
}
sort(p,p+cnt,cmp);
int t=0;
if(maxn<l||p[0].l>r)
{
printf("%lld\n",r-l+1);
continue;
}
while(t<cnt&&p[t].r<l)
t++;
long long ll=max(p[t].l,l),rr=min(p[t].r,r);
long long ans=rr-ll+1;
for(int i=t+1;i<cnt;i++)
{
if(rr==r) break;
if(p[i].l>r) break;
if(p[i].r<=rr) continue;
if(p[i].l<=rr) ll=rr+1;
else ll=p[i].l;
rr=p[i].r;
rr=min(p[i].r,r);
ans=ans+rr-ll+1;
}
printf("%lld\n",r-l+1-ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: