原题链接:蓝桥杯算法提高VIP-文化之旅
解题思路:
import java.util.*; //Dijksdra public class Main { static int[][] dis; static int[] minDis; static int N; public static void Dijksdra(int src) { int[] vis = new int[N+1]; for (int i = 1; i <= N; i++) minDis[i] = Integer.MAX_VALUE; minDis[src] = 0; for (int i = 1; i <= N; i++) { int u = -1; for (int j = 1; j <= N; j++) if (vis[j] == 0 && (u == -1 || minDis[u] > minDis[j])) u = j; vis[u] = 1; for (int j = 1; j <= N; j++) { if (vis[j] == 0 && dis[u][j] != 0 && minDis[u] != Integer.MAX_VALUE) minDis[j] = Math.min(minDis[u] + dis[u][j], minDis[j]); } } } public static void main(String args[]){ Scanner input = new Scanner(System.in); N = input.nextInt(); //国家数 int K = input.nextInt(); //文化数 int M = input.nextInt(); //道路数 int S = input.nextInt(); //起点 int T = input.nextInt(); //终点 int[] culture = new int[N+1]; for (int i = 1; i <= N; i++) culture[i] = input.nextInt(); int[][] isreject = new int[K+1][K+1]; for (int i = 1; i <= K; i++) for (int j = 1; j <= K; j++) isreject[i][j] = input.nextInt(); //文化i是否排斥j dis = new int[N+1][N+1]; minDis = new int[N+1]; for (int i = 1; i <= M; i++) { int l = input.nextInt(); int r = input.nextInt(); int d = input.nextInt(); //判断两个国家之间文化是否排斥 if (isreject[culture[r]][culture[l]] == 0) { if (dis[l][r] != 0) dis[l][r] = Math.min(dis[l][r], d); else dis[l][r] = d; } if (isreject[culture[l]][culture[r]] == 0) { if (dis[r][l] != 0) dis[r][l] = Math.min(dis[r][l], d); else dis[r][l] = d; } } Dijksdra(S); if (minDis[T] != Integer.MAX_VALUE) System.out.println(minDis[T]); else System.out.println(-1); } }
注意事项:
参考代码:
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复