public class Short {
public static void main(String args[]){
int n = 5;
int[] prev = new int[n+1];
int[] dist = {0,0,5000,5000,5000,5000};
int[][] c = {{0,0,0,0,0,0},{0,0,2,3,5000,5000},
{0,5000,0,1,2,5000},{0,5000,5000,0,9,2},
{0,5000,5000,5000,0,2},{0,5000,5000,5000,5000,0}};
/*
int n = 4;
int[] dist = {0,0,5000,5000,5000};
int[][] c = {{0,0,0,0,0},{0,0,2,3,5000},{0,5000,0,1,2},{0,5000,5000,0,9},{0,5000,5000,5000,0}};
*/
Graph g = new Graph(n,prev,c,dist);
g.shortestPath(1);
System.out.println(dist[n]);
}
}
class MinHeapNode{
int i; //顶点编号
int length; //当前路长
}
//循环队列
class CirQueue{
int size = 5000; //定义队列长度为1000
int front,rear;
MinHeapNode data[] = new MinHeapNode[size];
public CirQueue(){
front = rear = 0;
}
//元素入队操作
void queryIn(MinHeapNode e){
if((rear +1)%size == front){
System.out.println(“队列已满”);
}else{
rear = (rear+1)%size; //队尾指针在循环意义下加1
data[rear] = e; //在队尾插入元素
}
}
//元素出队操作
MinHeapNode queryOut(){
if(rear == front){
System.out.println(“队列已空”);
return null;
}else{
front = (front+1)%size; //队列在循环意义下加1
return data[front];
}
}
//读取队头元素,但不出队
MinHeapNode getQuery(){
if(rear == front){
System.out.println(“队列已空”);
return null;
}else{
return data[(front+1)%size];
}
}
//判断队列是否为空
boolean empty(){
return front == rear;
}
}
//图的表示
class Graph{
static int inf = 5000; //两点距离上界
int n; //图的顶点个数
int prev[]; //图的前驱顶点
int c[][]; //图的邻接矩阵
int dist[]; //最短距离数组
public Graph(int n,int[] prev,int[][] c,int[] dist){
this.n = n;
this.prev = prev;
this.c = c;
this.dist = dist;
}
/**
* 单源最短路径问题的优先队列式分支限界法
*/
public void shortestPath(int v){
//创建队列
CirQueue qq = new CirQueue();
//定义源为初始扩展结点
MinHeapNode e = new MinHeapNode();
e.i = v;
e.length = 0;
dist[v] = 0;
qq.queryIn(e);
//搜索问题的解空间
while(true){
for(int j = 1;j<=n;j++){
if(j>n){
break;
}
MinHeapNode m = qq.getQuery();
if((c[m.i][j]<inf)&&(m.length + c[m.i][j] < dist[j])){
//顶点i到顶点j可达,且满足控制约束
dist[j] = m.length + c[m.i][j];
prev[j] = m.i;
//加入活结点优先队列
MinHeapNode mi = new MinHeapNode();
mi.i = j;
mi.length = dist[j];
qq.queryIn(mi); //元素入队
}
}//for循环结束
qq.queryOut(); //当该结点的孩子结点全部入队后,删除该结点
if(qq.empty()){ //当队列为空时,算法结束
break;
}
}//while循环结束
}
}