题目描述
有N条线段,长度分别为a[1]-a[n]。
现要求你计算这N条线段最多可以组合成几个直角三角形。
每条线段只能使用一次,每个三角形包含三条线段。
输入描述
第一行输入一个正整数T(1<=T<=100),表示有T组测试数据.
对于每组测试数据,接下来有T行,
每行第一个正整数N,表示线段个数(3<=N<=20),接着是N个正整数,表示每条线段长度,(0<a[i]<100)。
输出描述
对于每组测试数据输出一行,每行包括一个整数,表示最多能组合的直角三角形个数
用例1
输入
1
7 3 4 5 6 5 12 13
输出
2
说明
可以组成2个直角三角形(3,4,5)、(5,12,13)
思路:递归回溯
1.定义一个集合 ,sides,用来保存每条边的平方,并按照从小到大排序
2.定义一个Set,保存每条边的平方,去重,方便后续剪枝
3.定义一个 boolean[] used = new boolean[n] ,标记每条边 sides 是否被使用
4.三层循环,每层循环计算一条边, 最后一层循环要 递归回溯
5.注意,从第二行开始,每一行的第一个数表示这一行有多少个有效数据 ,有效数据从第二个开始!!
import java.util.*;
public class Main{
// 递归回溯枚举三条边,并使用剪枝算法
public static int backtrack(List<Integer> segments, boolean[] used, Set<Integer> sideLengthSet) {
int res = 0;
int n = segments.size();
for (int i = 0; i < n - 2; i++) {
// 已使用
if (used[i]) continue;
for (int j = i + 1; j < n - 1; j++) {
// 已使用
if (used[j]) continue;
// 第三条边长度平方
int c = segments.get(i) + segments.get(j);
// 不存在指定边,剪枝
if (!sideLengthSet.contains(c)) continue;
for (int k = j + 1; k < n; k++) {
if (used[k]) continue;
// 剪枝:segments 递增,后续不可能等于 c 的边
if (segments.get(k) > c) break;
if (!segments.get(k).equals(c)) continue;
// 递归回溯
used[i] = used[j] = used[k] = true;
res = Math.max(res, backtrack(segments, used, sideLengthSet) + 1);
used[i] = used[j] = used[k] = false;
}
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // 读取测试组数
while (t-- > 0) {
int n = sc.nextInt();
// 存储输入边的平方,因为判断直接公式 a^2 + b^2 = c^2
List<Integer> sides = new ArrayList<>();
// 记录出现的边长数,用于后续剪枝
Set<Integer> sideLengthSet = new HashSet<>();
// 接收输入
for (int i = 0; i < n; i++) {
int tmp = sc.nextInt();
tmp *= tmp;
sides.add(tmp);
sideLengthSet.add(tmp);
}
// 排序
Collections.sort(sides);
// 标记每条边是否被使用
boolean[] used = new boolean[n];
int res = backtrack(sides, used, sideLengthSet);
System.out.println(res);
}
}
}