P3799 妖梦拼木棒
题目链接:
欲由4根木棒组成一个正三角形,则必有2根长度相等,且另外2根长度之和,等于前2根相等的木棒的长度。
由于各木棍的长度
外层循环为从长度为
内层循环为从剩余的木棍中取出两根长度之和为
①若
②若
一定注意随时取模。
#include <cstdio> #include <algorithm> using LL = long long; const int N = 1e5 + 5, mod = 1e9 + 7; int n, a[N], cnt[N];//cnt[i]表示长度为i的木棍个数 int main() { scanf("%d", &n); int min = 1e9, max = -1e9; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); cnt[a[i]]++; min = std::min(min, a[i]); max = std::max(max, a[i]); } LL ans = 0; for (int i = min; i <= max; i++) { if (cnt[i] >= 2) {//为保证可构成三角形,此长度的木棒数量 ≥2时才可进入内层循环。 LL times = cnt[i] * (cnt[i] - 1) / 2 % mod; for (int j = min; j <= i / 2; j++) {//为避免重复计算,规定j <= i - j if (j != i - j && cnt[j] >= 1 && cnt[i - j] >= 1) ans += times * cnt[j] * cnt[i - j] % mod; else if (j == i - j && cnt[j] >= 2) ans += times * (cnt[j] * (cnt[j] - 1) / 2) % mod; } } } printf("%lld", ans%mod); return 0; }
本文作者:胖柚の工作室
本文链接:https://www.cnblogs.com/pangyou3s/p/18016911
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步