多段图问题是DP的基础题目。大体的意思是有一个赋权有向图,其顶点集被分为几个子集。求经过每个子集从源点到终点的最短路径
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Scanner; 4 import java.util.Stack; 5 6 public class Main { 7 private static final int k = 3; 8 private static int[] P = new int[k]; 9 10 public static void MultiGraph(int[][] G,int n) 11 { 12 int[] COST = new int[n]; 13 14 Arrays.fill(COST,100); 15 int[] D = new int[n]; 16 int temp = 100; 17 COST[0]=0; 18 D[0]=0; 19 for(int j=1;j<n;j++) 20 { 21 for(int r = 0;r<j;r++) 22 { 23 24 if(G[j][r]!=0) 25 { 26 if(COST[j]>COST[r] + G[j][r]) 27 { 28 COST[j]=COST[r]+G[r][j]; 29 temp = r; 30 31 } 32 } 33 34 } 35 36 D[j] = temp; 37 } 38 P[k-1]=D[n-1]; 39 P[0]=0; 40 for(int j = 2;j>1;j--) 41 { 42 P[j-1] = D[P[j]]; 43 } 44 for (int te: P 45 ) { 46 System.out.println(te); 47 48 } 49 } 50 51 public static void main(String[] args) 52 { 53 //新建一个树 54 int[][] G = { 55 {0,2,3,4,0,0,0}, 56 {2,0,0,0,6,0,0}, 57 {3,0,0,0,5,0,0}, 58 {4,0,0,0,0,2,0}, 59 {0,6,5,0,0,0,3}, 60 {0,0,0,4,0,0,1}, 61 {0,0,0,0,3,1,0}, 62 }; 63 64 MultiGraph(G,7); 65 66 } 67 68 }
时间: 2024-10-21 17:00:55