time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
Like any unknown mathematician, Yuri has favourite numbers: A ,B, C, and D, where A≤B≤C≤D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A ≤ x ≤ B ≤ y ≤ C ≤ z ≤ D holds?
Yuri is preparing problems for a new contest now, so he is very busy. That’s why he asked you to calculate the number of triangles with described property.
The triangle is called non-degenerate if and only if its vertices are not collinear.
Input
The first line contains four integers: A, B, C and D (1≤A≤B≤C≤D≤5⋅105) — Yuri’s favourite numbers.
Output
Print the number of non-degenerate triangles with integer sides x, y, and z such that the inequality A ≤ x ≤ B ≤ y ≤ C ≤ z ≤ D holds.
input |
---|
1 2 3 4 |
output |
4 |
input |
---|
1 2 2 5 |
output |
3 |
input |
---|
500000 500000 500000 500000 |
output |
1 |
In the first example Yuri can make up triangles with sides (1,3,3), (2,2,3), (2,3,3) and (2,3,4).
In the second example Yuri can make up triangles with sides (1,2,2), (2,2,2) and (2,2,3).
In the third example Yuri can make up only one equilateral triangle with sides equal to 5⋅105.
这个题目我们分开来算,分别求出 x、y、z 可以取到的值的个数然后把三者做乘积,就可求得最终答案。(这个题我个人感觉更加偏向数学型的题目。)
因为
A ≤ x ≤ B , A ≤ x ≤ B, A≤x≤B, B ≤ y ≤ C B ≤ y ≤ C B≤y≤C
根据上式,我们可以得出 (x + y) 的范围是(令 (x + y)==i))
A + B ≤ i ≤ B + C A + B ≤ i ≤ B + C A+B≤i≤B+C
根据三角形的构成规则,两边之和一定要大于第三边,这个三角形才可以成立,也就是说 ( x + y ) 的值必须要比 z 的值要大( z的范围是[ C, D ] ),那么也就可以推导出下式:
C + 1 ≤ i ( i 是 等 于 x + y 的 ) C + 1 ≤ i (i 是等于 x+y 的) C+1≤i(i是等于x+y的)
因为如果 i 的值要比 C + 1 小的话(因为只能取整数),那么 i 最大只能取到C ,而这个时候 z 能取的最小值也是 C ,那么这个时候就变成了:
( x + y ) = = i ≤ C ≤ z ≤ D ( x + y ) == i ≤ C ≤ z ≤ D (x+y)==i≤C≤z≤D
很明显,这样就成了两边之和 ( x + y)小于第三边(z),这样就不能构成一个三角形。这时我们又得出 i 的另外一个限制条件,现在我们有两个 i 的限制条件了,我们大概可以把 i 的范围推一推了。
A + B ≤ i ≤ B + C A + B ≤ i ≤ B + C A+B≤i≤B+C C + 1 ≤ i C + 1 ≤ i C+1≤i
根据这两个不等式我们可以准确的推出 i 的范围
m a x ( A + B , C + 1 ) ≤ i ≤ B + C max( A+B, C + 1) ≤ i ≤ B + C max(A+B,C+1)≤i≤B+C
用代码表示就是这样:
for (ll i = max(C+1,A+B); i <= B+C; i++)
只有取 A+B 和 C+1 当中的较大的那个数,才能保证 i 的值是大于 C ( z可以取到的最小值)。
现在我们已经确定了 x+y 的取值范围,那么我们一个个取遍历 x+y 可以取到的值(把 x+y 看成是不变的一个数),每 x+y 取到一个数对应的 z 的值的变化范围也就可以根据 x+y 确定下来。
下面我们来固定一个 x+y 的值,来推导一下这个固定的 x+y 值下对应的 z 可以取到的值的变化范围。我们分两种情况来分析:
#include
using namespace std;
typedef long long ll;
ll A,B,C,D;
ll x,y,z;
int main()
{
ll res = 0;
scanf("%d %d %d %d",&A,&B,&C,&D);
for (ll i = max(C+1,A+B); i <= B+C; i++)
{
ll ymin = max(i-B,B);
ll ymax = min(i-A,C);
res += (ymax - ymin + 1)*min(i-C,D-C+1);
}
printf("%lld",res);
system("pause");
return 0;
}
A, B, C, D = map(int,input().split())
res = 0
for i in range(max(C+1,A+B),B+c+1)
ymin = max(i - B, B)
ymax = min(i - A,C)
res += (ymax - ymin + 1)*min(i-C,D-C+1)
print(res) # python代码没有提交测试,不知道准确性如何