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

154 篇文章 1 订阅
7 篇文章 0 订阅

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<bits/stdc++.h>
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺 崽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值