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; }
合集:
前缀和、差分
, codeforces
分类:
刷题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架