Wool
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 588 Accepted Submission(s): 167
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.
思路:先排序,然后找出每相邻的树枝可构成三角形的范围,主要问题在于求所有的并集后与现有树枝的交的以外的部分。
对该问题方法:从最后一个逐个去除相邻范围,因为按照升序排列,最大值一直在减小我们只需把右边界一点一点去除即可,每次多出的右边界作为一部分逐渐累加。
下面ac代码
#include<bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 100000 + 10;
LL num[maxn];
int main()
{
int T;
cin>>T;
while(T--)
{
LL n , L , R;
cin>>n>>L>>R;
for(int i = 1 ; i <= n ; ++i)
{
scanf("%I64d" , &num[i]);
}
sort(num + 1 , num + n + 1);
LL ans = 0;
for(int i = n ; i >= 2 ; --i)
{
LL r = num[i] + num[i - 1] - 1;
LL l = num[i] - num[i - 1] + 1;
if(l > R || r < L)continue;
if(r < R)
{
ans += R - r ; /如果右边界有剩余累加
}
R = l - 1; // 修改右边界
if(R < L)
break; //线段已经不存在时候停止。
}
if(R >= L)
ans += R - L + 1;// 若线段最后有剩余。
cout<<ans<<endl;
}
return 0;
}