Input
t组数据,每组数据包含
n根棒子,每个棒子长度为2的ai次方,写一个程序找出它们能组成的三角形的数量
Output
For each test case, print one integer — the number of ways to choose exactly 33 sticks so that a triangle can be formed out of them.
Example
input
Copy
4
7
1 1 1 1 1 1 1
4
3 2 1 3
3
1 2 3
1
1
output
Copy
35 2 0 0
Note
In the first test case of the example, any three sticks out of the given 77 can be chosen.
In the second test case of the example, you can choose the 11-st, 22-nd and 44-th stick, or the 11-st, 33-rd and 44-th stick.
In the third test case of the example, you cannot form a triangle out of the given sticks with lengths 22, 44 and 88.
思路
因为长度是2的ai次方,所以能组成三角形的组合只能是三根一样长或者两根一样长和一根长度小于他们的棒子
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll cnm(ll shu, ll a) { //计算组合数的函数
if (shu == 1) {
return 0;
}
ll sum = 1;
for (int i = 0; i < a; i++) {
sum *= (shu - i);
}
for (int i = 1; i <= a; i++) {
sum /= i;
}
return sum;
}
int main() {
int t;
cin >> t;
while (t--) {
ll n;
cin >> n;
vector<ll>a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
ll ans = 0;
sort(a.begin(), a.end());//从小到大排序
ll s = n, d = 1;//s为比当前这一组小的棒子有几根,d为当前相同大小的棒子有几根
for (ll i = n - 1; i > 0; i--) {//从后往前遍历
if (a[i] == a[i - 1]) {//相同,d加一
s--;
d++;
} else {//不同,计算这一组的结果
ans += cnm(d, 3);
ans += cnm(d, 2) * (s - 1);
s--;
d = 1;
}
}
ans += cnm(d, 3);//计算最后一组的结果
printf("%lld\n", ans);
}
}