题目:P3799 妖梦拼木棒 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
思路:四根木棍拼成一个等边三角形,自然可以想到两根一样长,剩下两根加起来也为此长度即可。利用桶来存下各个从长度木棍的数量,两层循环枚举长度即可,外层循环枚举较长的那两根的长度,内层循环枚举第三边的其中一部分的长度,记得长度一定要为正数。
以下是ac代码(附带详细注释)
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define res(i,a,b) for(int i=(a);i<=(b);i++)
#define los(i,a,b) for(int i=(a);i<(b);i++)
#define dwn(i,a,b) for(int i=(a);i>=(b);i--)
#define el '\n'
using namespace std;
using LL = long long;
const int p = 1e9 + 7, Max = 5e3 + 5;
LL n, ans = 0;
LL a, maxx = 0, num[Max];
//!!!组合数的算法,由于这题都是选1或者2,所以可以简写乘c(x,2)=x*(x-1)/2,c(x,1)=x,自己推一下就出来了。
int main()
{
memset(num, 0, sizeof(num));
cin >> n;
res(i, 1, n)
{
scanf("%lld", &a);
num[a]++;//记录数量
maxx = max(maxx, a);//求出木棍的最长值
}
//外层表示两根长度为i的木棍,里层表示一根长度为j,一根为i-j
res(i, 2, maxx)//就是for(int i=2;i<=maxx;i++)
{
if (num[i] < 2)//外层循环是两根一样长的木棍,所以至少要两根
continue;
res(j, 1, i / 2)
{
if (i == 2 * j && num[j] > 1)//刚好是两倍,j的数量大于2,那直接拼
ans = ans + (num[i] * (num[i] - 1) / 2 % p * (num[j] * (num[j] - 1) / 2) % p) % p;
else if (i != 2 * j && num[j] && num[i - j])//不是两倍,就各取一根
ans = ans + (num[i] * (num[i] - 1) / 2 % p * (num[j] * num[i - j] % p)) % p;
}
ans %= p;//按题意取模
}
cout << ans << el;
}