容斥 + 组合数学 ---Codeforces Round #317 A. Lengthening Sticks
Lengthening Sticks#
Problem's Link: http://codeforces.com/contest/571/problem/A
#
Mean:
给出a,b,c,l,要求a+x,b+y,c+z构成三角形,x+y+z<=l,成立的x,y,z有多少种。
analyse:
这题在推公式的时候细心一点就没问题了。
基本的思路是容斥:ans=所有的组合情况-不满足条件的情况。
1.求所有的组合情况
方法是找规律:
首先只考虑l全部都用掉的情况。
l=1:3
l=2:6
l=3:10
l=4:15
......
到这可能你会发现,其实l=i时,结果就是1+2+...+(i+1),即:C(i+2,2),也就是三角数。
然而i可以取0~l中的任何一个,那也很简单,一路累加上去就可。
2.不满足条件的情况:
三角形满足的条件是什么?任意两边之和大于第三边,那么不满足的必要条件就是第三边小于等于其它两边之和。
分别枚举a,b,c做第三边的情况,再考虑将剩下的l拆分三份分配给a,b,c依旧不满足的情况即可。
Time complexity: O(N)
Source code:
/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-08-23-12.24
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
LL cal(LL a,LL b,LL c,LL l)
{
LL ans=0;
for(LL i=max(b+c-a,0LL);i<=l;++i)
{
LL x=min(l-i,a+i-b-c);
ans+=(1+x)*(2+x)/2;
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
LL a,b,c,l;
cin>>a>>b>>c>>l;
LL ans=0;
for(LL i=0;i<=l;++i)
ans+=LL(1+i)*(2+i)/2;
ans-=cal(a,b,c,l);
ans-=cal(b,a,c,l);
ans-=cal(c,a,b,l);
cout<<ans;
return 0;
}
/*
*/
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-08-23-12.24
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
LL cal(LL a,LL b,LL c,LL l)
{
LL ans=0;
for(LL i=max(b+c-a,0LL);i<=l;++i)
{
LL x=min(l-i,a+i-b-c);
ans+=(1+x)*(2+x)/2;
}
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
LL a,b,c,l;
cin>>a>>b>>c>>l;
LL ans=0;
for(LL i=0;i<=l;++i)
ans+=LL(1+i)*(2+i)/2;
ans-=cal(a,b,c,l);
ans-=cal(b,a,c,l);
ans-=cal(c,a,b,l);
cout<<ans;
return 0;
}
/*
*/
作者:北岛知寒
出处:https://www.cnblogs.com/crazyacking/p/4752314.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?