Codeforces Round #643 (Div. 2) C.Count Triangles

Codeforces Round #643 (Div. 2) C.Count Triangles

题目链接
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≤5e5) — 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.

Examples

input

1 2 3 4

output

4

input

1 2 2 5

output

3

input

500000 500000 500000 500000

output

1

早知道搞D了,赛后发现D的过题人数是C的两倍,真的吐了
这题必须要考虑 O(n) 的算法,即只能考虑一个区间,我选择的是 [ A , B ] [A,B] [A,B]~
即从 [ A , B ] [A,B] [A,B] 选一条边 i i i 作为最小边,然后我们可以通过区间 [ B , C ] [B,C] [B,C] 求出最大边的范围即 [ B + i − 1 , C + i − 1 ] [B+i-1,C+i-1] [B+i1,C+i1],下面就是和区间 [ C , D ] [C,D] [C,D] 取交集 S S S,不难发现,交集 S S S 是可以通过求和公式快速计算的,下面考虑两种极端情况:
1. B + i − 1 ≥ D B+i-1\geq D B+i1D,此时答案 a n s = a n s + ( D − C + 1 ) ∗ ( C − B + 1 ) ans=ans+(D-C+1)*(C-B+1) ans=ans+(DC+1)(CB+1)
2. C + i − 1 ≥ D C+i-1\geq D C+i1D,此时答案 a n s = a n s + ( D − C + 1 ) ∗ ( C + i − 1 − D ) ans=ans+(D-C+1)*(C+i-1-D) ans=ans+(DC+1)(C+i1D)
AC代码如下:

#include
using namespace std;
typedef long long ll;

main(){
    ll a,b,c,d;
    cin>>a>>b>>c>>d;
    ll ans=0;
    for(ll i=a;i<=b;i++){
        ll mn=i+b-1,mx=i+c-1;
        if(mn>=d) ans+=(d-c+1)*(c-b+1);
        else{
            ll l=max(mn,c),r=min(d,mx);
            ans+=(r-l+1)*(l-c+1+r-c+1)/2;
            if(mx>d) ans+=(mx-d)*(d-c+1);
        }
    }
     cout<<ans;
}

你可能感兴趣的:(Codeforces,思维,计数)