已知平面上若干個點的座標。
須要求出在全部的組合中,4個點間平均距離的最小值(四捨五入,保留2位小數)。
好比有4個點:a,b,c,d, 則平均距離是指:ab, ac, ad, bc, bd, cd 這6個距離的平均值。
每一個點的座標表示爲:橫座標,縱座標
座標的取值範圍是:1~1000
例如,若是程序輸入:
10,10
20,20
80,50
10,20
20,10
則程序應該輸出:
11.38
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class MinDistance { /** * @param args */ private ArrayList<Point> list = new ArrayList<Point>(); private HashMap<String,Double> map = new HashMap<String,Double>(); private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public void input() throws NumberFormatException, IOException{ String str = null; while(!(str=in.readLine()).equals("")){ String[] strs = str.split(","); int x = Integer.parseInt(strs[0]); int y = Integer.parseInt(strs[1]); Point p = new Point(x,y); list.add(p); } System.out.println(list.size()); /* for(Point p:list){ System.out.println(p.x+","+p.y); } */ } public void process(){ int[] ind = null; double min = Double.MAX_VALUE; for(int i=0;i<list.size();i++){ int[] indexs = new int[4]; indexs[0] = i; double distance = 0; for(int j=1;j<4;j++){ double d = Double.MAX_VALUE; for(int k=0;k<list.size();k++){ boolean b = true; for(int m=0;m<j;m++){ if(k==indexs[m]){ b=false; break; } } if(b){ Double sum = 0.0; for(int m=0;m<j;m++){ String s1 = indexs[m]+""+k; String s2 = k+""+indexs[m]; Double num = null; if((num=map.get(s1))==null&&(num=map.get(s2))==null){ num = Math.pow(list.get(k).x-list.get(indexs[m]).x, 2)+Math.pow(list.get(k).y-list.get(indexs[m]).y, 2); map.put(s1, num); } sum+=num; } if(sum<d){ d=sum; indexs[j]=k; } } } distance+=d; } if(distance<min){ min = distance; ind = indexs; } } double dis = 0; for(int i=0;i<4;i++){ for(int j=i+1;j<4;j++){ String s1 = ind[i]+""+ind[j]; String s2 = ind[j]+""+ind[i]; Double dou = map.get(s1); if(dou==null) dou=map.get(s2); dis+=Math.sqrt(dou); } } System.out.printf("%.2f", dis/6.0); } public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub MinDistance md = new MinDistance(); md.input(); md.process(); } class Point{ int x=0; int y=0; public Point(int x,int y){ this.x = x; this.y = y; } } }