题目描述
输入N个互不相同的二维整数坐标,求这N个坐标可以构成的正方形数星。(内积为零的的两个向量垂直)
输入描述
第─行输入为N,N代表坐标数量,N为正整数, N≤ 100
之后的N行输入为坐标xy以空格分隔,x,y为整数,-10≤x,y ≤10
输出描述
输出可以构成的正方形数量
用例
输入
3
1 3
2 4
3 1
输出
0
说明
3个点不足以构成正方形
输入
4
0 0
1 2
3 1
2 -1
输出
1
这里我又加了一个案例,使题目问题更加具体
输入
4
0 0
1 2
3 1
2 -1-2 1
-1 3
输出
2
说明
此4点可构成正方形
注:以下代码是我硬莽出来的,解题代码比较稚嫩,代码性能优化不是太好,如果,有问题请多包涵!
java代码
标签:24,count,Java,int,OD,new,util,import,java From: https://blog.csdn.net/lovely_compiler/article/details/145311503package odTest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class square { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int inputNum = Integer.parseInt(scanner.nextLine()); List<int[]> list = new ArrayList<int[]>();//存放输入的 坐标 boolean[] hasUsed = new boolean[inputNum]; while(inputNum>0) { int[] index = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); list.add(index); inputNum--; } int count = 0;//记录有几个正方形 count = copeData(list,new ArrayList<int[]>(),count,hasUsed,0,new HashSet<Integer>()); System.out.println(count); } //list 存放输入的坐标,arraylist存放正方形的四个顶点, //hasUse过滤使用过的点(防止重复用点,内存溢出), //judgeNum和containJudge:避免重复鉴定四个顶点,下标之和具有唯一性,避免反复鉴定, private static int copeData(List<int[]> list, ArrayList<int[]> arrayList, int count, boolean[] hasUsed, int judgeNum,HashSet<Integer> containJudge) { if(arrayList.size()==4 && !containJudge.contains(judgeNum)) { containJudge.add(judgeNum); count = judgeSquare(arrayList)? count+1:count; return count; }else if(arrayList.size()==4){ return count; } for(int i = 0;i<list.size();i++) { if(hasUsed[i] == true) { continue; } hasUsed[i] = true; arrayList.add(list.get(i)); judgeNum = judgeNum+i; count = copeData(list,arrayList,count,hasUsed,judgeNum,containJudge); hasUsed[i] = false; arrayList.remove(arrayList.size()-1); judgeNum = judgeNum-i; } return count; } //判断内积是否为0 private static boolean judgeSquare(ArrayList<int[]> arrayList) { int countRect = 0; List<Integer> vectorList = new ArrayList<Integer>(); for(int i=0;i<arrayList.size();i++) { for(int j=i+1;j<arrayList.size();j++) { //获取两点之间的距离 int straightLine = (arrayList.get(i)[0]-arrayList.get(j)[0])*(arrayList.get(i)[0]-arrayList.get(j)[0]) +(arrayList.get(i)[1]-arrayList.get(j)[1])*(arrayList.get(i)[1]-arrayList.get(j)[1]); if(!vectorList.contains(straightLine)) { vectorList.add(straightLine); }else { countRect++; } if(countRect == 4) { return true; } } } return false; } }