C. Count Triangles

原题链接

题解

假设 sum 数组是从当最大边不超过 i 时边 C 的取值个数

遍历边 a,边 b
当 a+b==r 时 ans+=a[r];此时时间复杂度为O(n*n)

优化:
定义 s 数组是 a 数组的前缀和

则当b在B~C中遍历时,ans+=s[a+C]-s[a+B-1],优化一个O(n

code

 

复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+5;
ll s[N];
int main(){
//    freopen("input.txt","r",stdin);
    ios::sync_with_stdio(false);
    ll a,b,c,d;
    cin>>a>>b>>c>>d;
    ll ans=0ll;
    s[c]=0;   
    for (int i=c+1;i<=b+c;i++){
        if (i>d) s[i]=s[i-1]+d-c+1ll;
        else s[i]=s[i-1]+i-c;
    }
    for (int i=a;i<=b;i++){
        if (i+b>d) ans+=(d-c+1ll)*(c-b+1ll);
        else if (i+b>c) ans+=s[i+c]-s[i+b-1];
        else ans+=s[i+c];
//        cout<<ans<<" ";
    }
//    cout<<endl;
    cout<<ans<<endl;
    return 0;
} 
复制代码

 

posted @   黑屿白  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示