package B29_jiaquantu;
import B28_tujiqiyingyong.UnweightedGraph;
import B28_tujiqiyingyong.Edge;
import java.util.*;
/**
* @author Fjj
* @Time 2023/3/18 19:48
* @title WeightedGraph
* @Software: IntelliJ IDEA
* @description TODO
*/
public class WeightedGraph<V> extends UnweightedGraph<V> {
/** Construct an empty */
public WeightedGraph(){}
/** Construct a WeightedGraph from vertices and edged in arrays */
public WeightedGraph(V[] vertices, int[][] edges){
createWeightedGraph(java.util.Arrays.asList(vertices), edges);
}
/** Construct a WeightedGraph from vertices and edges in list */
public WeightedGraph(int[][] edges, int numberOfVertices){
List<V> vertices = new ArrayList<>();
for (int i = 0; i < numberOfVertices; i++)
vertices.add((V)(Integer.valueOf(i)));
createWeightedGraph(vertices, edges);
}
/** Construct a WeightedGraph for vertices 0, 1, 2 and edge list */
public WeightedGraph(List<V> vertices, List<WeightedEdge> edges){
createWeightedGraph(vertices, edges);
}
/** Construct a WeightedGraph from vertices 0, 1 and edge array */
public WeightedGraph(List<WeightedEdge> edges, int numberOfVertices){
List<V> vertices = new ArrayList<>();
for (int i = 0; i < numberOfVertices; i++)
vertices.add((V)(Integer.valueOf(i)));
createWeightedGraph(vertices, edges);
}
/** Create adjacency lists from edge arrays */
private void createWeightedGraph(List<V> vertices, int[][] edges){
this.vertices = vertices;
// create a list for vertices
for (int i = 0; i < vertices.size(); i++){
neighbors.add(new ArrayList<Edge>());
}
// put WeightedEdge in these neighbors
for (int i = 0; i < edges.length; i++){
neighbors.get(edges[i][0]).add(new WeightedEdge(edges[i][0], edges[i][1], edges[i][2]));
}
}
/** Create adjacency lists from edge lists */
private void createWeightedGraph(List<V> vertices, List<WeightedEdge> edges){
this.vertices = vertices;
for (int i = 0; i < vertices.size(); i++)
neighbors.add(new ArrayList<Edge>());
for (WeightedEdge edge: edges)
neighbors.get(edge.u).add(edge);
}
/** Return the weight on the edge (u, v) */
public double getWeight(int u, int v) throws Exception{
for (Edge edge : neighbors.get(u)){
if (edge.v == v){
return ((WeightedEdge)edge).weight;
}
}
throw new Exception("Edge does not exit");
}
/** Display edges with weights 返回所有的边和权重 */
public void printWeightedEdges(){
for (int i = 0; i < getSize(); i++){
System.out.print(getVertex(i) + " (" + i + "): " );
for (Edge edge: neighbors.get(i)){
System.out.print("(" + edge.u + ", " + edge.v + ", " + ((WeightedEdge)edge).weight + ") ");
}
System.out.println();
}
}
/** Add edges to the weighted graph */
public boolean addEdge(int u , int v, double weight) throws IllegalArgumentException{
if (u < 0 || u > getSize() - 1)
throw new IllegalArgumentException("No such index: " + u);
if (v < 0 || v > getSize() - 1)
throw new IllegalArgumentException("No such index: " + v);
WeightedEdge e = new WeightedEdge(u, v, weight);
if (!neighbors.get(u).contains(e))
return addEdge(e);
else
return false;
}
/** Get a minimum spanning tree rooted at vertex 0 返回一个从节点0开始的最小生成树 */
public MST getMinimumSpanningTree(){
return getMinimumSpanningTree(0);
}
/** Get a minimum spanning tree rooted at a specified vertex 返回一个从节点v开始的最小生成树 */
// 最小生成树, 最大生成树反着来, Double.NEGATIVE_INFINITY;无穷小
public MST getMinimumSpanningTree(int startingVertex){
// cost[v] stores the cost by adding v to the tree cost[v]通过将v添加到树中来存储成本 cost
// 用于存储 与当前连接的点的 对应的点的 权重
double[] cost = new double[getSize()];
// for (int i = 0; i < cost.length; i++){
// cost[i] = Double.POSITIVE_INFINITY; // Initial cost
// }
// Initial cost
Arrays.fill(cost, Double.POSITIVE_INFINITY);
// 刚开始的 那个点的权重 设置为0 用于刚进去的时候 的点的添加
cost[startingVertex] = 0; // cost of source is 0
int[] parent = new int[getSize()]; // Parent of a vertex
parent[startingVertex] = -1; // startingVertex is the root
double totalWeight = 0; // Total weight of the tree thus far
// 这里面存储的 就是路线,也就是最小的那些连接线
// 使用线性表而不是集合 是因为要记录加入到T的顶点的次序
List<Integer> T = new ArrayList<>();
// Expand T
while (T.size() < getSize()){
// Find smallest cost u in V - T
int u = -1; // Vertex to be detemrined 要确定的顶点
double currentMinCost = Double.POSITIVE_INFINITY;
for (int i = 0; i < getSize(); i++){
// 这里查看 T路径中有没有当前的顶点 与 当前顶点的权重和 当前最小的权重做比较
if (!T.contains(i) && cost[i] < currentMinCost){
currentMinCost = cost[i];
u = i;
}
}
// 如果点全部添加进去 推出while循环 ,没有添加 顶点u到T路径中
if (u == -1) break; else T.add(u); // Add a new Vertex to T
// 添加权重
totalWeight += cost[u]; // Add cost[u] to the tree
// Adjust cost[v] for v that is adjacent to u and v in V - T
// 遍历当前的顶点 连接的边
for (Edge e: neighbors.get(u)){
// e.u = u e.v = v 就是与u 连接的顶点
// 找到没有存在 T路径中的与u 连接的顶点 并且这个顶点如果是无穷大的 也就是大于 这条边的权重
// 这里就是寻找 如果出现了 比之前还要小的权重,要刷新一哈 给cost[e.v]赋值过去, 并确定父亲节点
if (!T.contains(e.v) && cost[e.v] > ((WeightedEdge)e).weight){
// 直接将这表边的权重 赋值给 该顶点对应cost中的值
cost[e.v] = ((WeightedEdge)e).weight;
// 将u赋值为 e.v顶点的父节点
parent[e.v] = u;
}
}
}
return new MST(startingVertex, parent, T, totalWeight);
}
public MST getMaximumSpanningTree(){
return getMaximumSpanningTree(0);
}
// 最大生成树, 从根节点出发,到叶子节点的时候 权重之和最大
public MST getMaximumSpanningTree(int startingVertex){
// 首先需要 定义一个 cost[] 用于储存 当前的点 对应点的 权重之和
double[] cost = new double[getSize()];
// 这里 初始化为 最小的 方便后面进行 小于比较 找最大的
Arrays.fill(cost, Double.NEGATIVE_INFINITY);
// 初始化 第一个点的权重
cost[startingVertex] = 0;
// 定义parent数组 用于存储 父亲节点
int[] parent = new int[getSize()];
// 将startingVertex 指定为根节点 => 赋值为-1
parent[startingVertex] = -1;
// 定义totalWeight 用于存储 总的权重
double totalWeight = 0;
// 定义T 线性表 用于存储 路径
List<Integer> T = new ArrayList<>();
// 进入循环,开始进行 权重的判断与连接
while (T.size() < getSize()){
// 确定当前的顶点
int u = -1;
// 初始化 currentWeight 用于获取最大的 初始化为NEGATIVE_INFINITY
double currentWeight = Double.NEGATIVE_INFINITY;
// 进行遍历 判断 权重 获取最大的权重
for (int i = 0; i < getSize(); i++){
// 怎么判断 这个 cost[i] >< currentWeight 看 -1 与 无穷大和无穷小
if (!T.contains(i) && cost[i] > currentWeight){
// 将当前节点的权重 赋值为 cost[i]的值
currentWeight = cost[i];
u = i;
}
}
// 如果 没有进去 上面那个if判断 全部节点放在这里面 退出循环
// 不是就将 u加入到 T路径中
if (u == -1) break; else T.add(u);
// 这里是将 与 u进行连接的 边的 权重 赋值给 与u进行连接的 点 对应的 cost[e.v]
for (Edge e: neighbors.get(u)){
if (!T.contains(e.v) && cost[e.v] < ((WeightedEdge)e).weight){
cost[e.v] = ((WeightedEdge)e).weight;
// 上面就是获取 较之前大的权重
// 下面就是 确定 u 为 e.v 的父亲节点
parent[e.v] = u;
}
}
}
return new MST(startingVertex, parent, T, totalWeight);
}
/** MST is an inner class in WeightedGraph */
public class MST extends SearchTree {
private double totalWeight;
public MST(int root, int[] parent, List<Integer> searchOrder, double totalWeight) {
super(root, parent, searchOrder);
this.totalWeight = totalWeight;
}
public double getTotalWeight(){
return totalWeight;
}
}
public ShortestPathTree getShortestPath(){
return getShortestPath(0);
}
/** Find single-source shortest paths 返回所有的单元最短路径 */
public ShortestPathTree getShortestPath(int sourceVertex){
// cost[v] stores the cost of the path from v to the source
// cost[v]存储从v到源的路径的成本
double[] cost = new double[getSize()];
// 初始化最大值 方便判断 获取 最小值
Arrays.fill(cost, Double.POSITIVE_INFINITY);
// Cost of source is 0
cost[sourceVertex] = 0;
// parent[v] stores the previous vertex of v in the path
int[] parent = new int[getSize()];
parent[sourceVertex] = -1;
// T stores the vertices whose path found so far
List<Integer> T = new ArrayList<>();
// Expand T
while (T.size() < getSize()){
// Find smallest cost u in V-T
int u = -1; // 当前节点
double currentMinCost = Double.POSITIVE_INFINITY; // 当前节点对应的 权重
for (int i = 0; i < getSize(); i++){
if (!T.contains(i) && cost[i] < currentMinCost){
currentMinCost = cost[i];
u = i;
}
}
if (u == -1) break; else T.add(u);
// Adjust cost[v] for v that is adjacent to u and v in V-T
for (Edge e: neighbors.get(u)){
if (!T.contains(e.v) && cost[e.v] > cost[e.u] + ((WeightedEdge)e).weight){
cost[e.v] = cost[e.u] + ((WeightedEdge)e).weight;
parent[e.v] = u;
}
}
}
return new ShortestPathTree(sourceVertex, parent, T, cost);
}
/** ShortestPathTree is an inner class in WeightedGraph ShortestPathTree是WeightedGraph中的一个内部类 */
public class ShortestPathTree extends SearchTree{
// cost[v] is the cost from v to source
// cost数组是 将 从v根源顶点出发的 存储所有节点(最短)路径和
private double[] cost;
/** Construct a path */
public ShortestPathTree(int root, int[] parent, List<Integer> searchOrder, double[] cost) {
super(root, parent, searchOrder);
this.cost = cost;
}
/** Return the cost for a path from the root to vertex v 返回从root到 节点v的 cost的值(最短路径) */
public double getCost(int v){
return cost[v];
}
/** Print paths from all vertices to the source 打印所有的路径 从根源点 出发的 */
public void printAllPaths(){
System.out.println("All shortest paths from " + vertices.get(getRoot()) + " are: ");
for (int i = 0; i < cost.length; i++){
printPath(i); // Print a path from i to the source
System.out.println("(cost: " + cost[i] + ")"); // Path cost
}
}
}
}