欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

蓝桥杯练习算法提高Car的旅行路线Java

时间:2023-07-08

import java.util.Scanner;public class oiergiv { static class City{ int []x = new int[4]; int []y = new int[4]; int price; public City(int x1, int y1, int x2, int y2, int x3, int y3, int price) { x[0] = x1; y[0] = y1; x[1] = x2; y[1] = y2; x[2] = x3; y[2] = y3; double t12 = distance(x1,y1,x2,y2); double t13 = distance(x1,y1,x3,y3); double t23 = distance(x2,y2,x3,y3); //计算另一个机场的坐标 if(Math.abs(t12*t12+t13*t13-t23*t23)<0.000001){ x[3] = x2+x3-x1; y[3] = y2+y3-y1; } if(Math.abs(t12*t12+t23*t23-t13*t13)<0.000001){ x[3] = x1+x3-x2; y[3] = y1+y3-y2; } if(Math.abs(t13*t13+t23*t23-t12*t12)<0.000001){ x[3] = x1+x2-x3; y[3] = y1+y2-y3; } this.price = price; } //计算机场之间的距离 private double distance(int x12, int y12, int x22, int y22) { return Math.sqrt((x22-x12)*(x22-x12)+(y22-y12)*(y22-y12)); } } static int s,t,A,B; public static void main(String[] args){ Scanner sc = new Scanner(System.in); s = sc.nextInt(); t = sc.nextInt(); A = sc.nextInt(); B = sc.nextInt(); double[][] price = new double[s*4][s*4];//机场图(所有机场都联通,不用赋INF) City []cities = new City[s];//城市数组 for (int i = 0; i < s; i++) {//下标0-1-2对应1-2-3城市编号 int x1 = sc.nextInt(); int y1 = sc.nextInt(); int x2 = sc.nextInt(); int y2 = sc.nextInt(); int x3 = sc.nextInt(); int y3 = sc.nextInt(); int train_price = sc.nextInt(); City citys = new City(x1, y1, x2, y2, x3, y3, train_price); cities[i] = citys;//将每个城市封装为一个对象 } //邻接矩阵存机场图,价格是权值 for(int i = 0;i < s*4;i++){ for(int j = 0;j < s*4;j++){ if(i/4 == j/4){//如果是同城的机场,×的是高铁价格 price[i][j] = dist(cities[i/4].x[i%4],cities[i/4].y[i%4],cities[j/4].x[j%4],cities[j/4].y[j%4])*cities[i/4].price; }else{//如果是不同城的机场,×的是飞机价格 price[i][j] = dist(cities[i/4].x[i%4],cities[i/4].y[i%4],cities[j/4].x[j%4],cities[j/4].y[j%4])*t; } } } floyd(price); //最后还要找出最小值,因为是飞两座城市之间的最小价格,而不是机场之间 double min = price[(A-1)*4][(B-1)*4]; for(int i = (A-1)*4; i < A*4; i++){ for(int j = (B-1)*4; j < B*4; j++){ min = Math.min(price[i][j],min); } } System.out.printf("%.1f", min); } public static void floyd(double[][] price){ //floyd的三段for for (int k = 0; k < s*4; k++) { for (int i = 0; i < s*4; i++) { for (int j = 0; j < s*4; j++) { price[i][j] = Math.min(price[i][j], price[i][k] + price[k][j]); } } } } //计算机场之间的距离,计算价格 private static double dist(int x12, int y12, int x22, int y22) { return Math.sqrt((x22-x12)*(x22-x12)+(y22-y12)*(y22-y12)); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。