题目:
给定一个长度为 m 的数组 a0,a1,…,am−1。
如果数组中有 ai+aj=ak 其中 i,j,ki 大于等于 0 并且小于 m,则称 (ai,aj,ak)为一个三元组。
现在,给定你数组 a,请你计算其中三元组的个数。
例如,当 m=2,数组 a 为 {0,0} 时,所有三元组为:
- (a0,a0,a0)
- (a0,a0,a1)
- (a0,a1,a0)
- (a0,a1,a1)
- (a1,a0,a0)
- (a1,a0,a1)
- (a1,a1,a0)
- (a1,a1,a1)
共计 8个三元组。
输入格式
第一行包含一个整数 n,表示共有 n 组测试数据。
每组数据第一行包含整数 m,表示数组长度。
第二行包含 m 个整数,表示数组。
输出格式
每组数据输出一行一个答案,表示三元组个数。
数据范围
1≤n≤10,
1≤m≤50,
数组元素取值范围 [0,100]。
输入样例:
2
2
0 0
5
1 1 1 2 1
输出样例:
8
16
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 55,M = 210;
int n, m;
int w[N], cnt[M];
int main()
{
scanf("%d",&n);
while (n -- )
{
scanf("%d", &m);
memset(cnt, 0, sizeof cnt);
for(int i = 0; i < m; i ++ )
{
scanf("%d", &w[i]);
cnt[w[i]]++;
}
int res = 0;
for(int i = 0; i < m; i ++ )
for(int j = 0; j < m; j ++ )
res += cnt[w[i]+w[j]];
printf("%d\n", res);
}
return 0;
}
题目比较简单,不再赘述
该程序解决了一个数组中三元组计数的算法问题。对于给定长度的数组,计算所有满足条件ai+aj=ak的三元组数量,并对测试数据进行处理。程序使用哈希表加速计算,对于每一对(i,j),直接查询哈希表中对应和的计数。
11万+

被折叠的 条评论
为什么被折叠?



