#include <stdio.h> #include <queue> using namespace std; #define MAX 11 #define INF 0x3f3f3f3f //问题表示 int A[MAX][MAX]={ //一个带权有向图 {0,1,4,INF,INF}, {INF,0,INF,1,5}, {INF,INF,0,INF,1}, {INF,INF,2,0,3}, {INF,INF,INF,INF,INF} }; int n=5; //求解结果表示 int bestlen=INF; //最优路径的路径长度 int bestcount=0; //最优路径的条数 struct NodeType { int vno; //顶点的编号 int length; //当前结点的路径长度 bool operator<(const NodeType &s) const //重载>关系函数 { return length>s.length; } //length越小越优先 };转Java语言
时间: 2024-02-10 10:32:42 浏览: 30
import java.util.*;
public class Main {
private static final int MAX = 11;
private static final int INF = 0x3f3f3f3f;
private static int[][] A = {{0, 1, 4, INF, INF},
{INF, 0, INF, 1, 5},
{INF, INF, 0, INF, 1},
{INF, INF, 2, 0, 3},
{INF, INF, INF, INF, INF}};
private static int n = 5;
private static int bestlen = INF;
private static int bestcount = 0;
private static class NodeType implements Comparable<NodeType> {
int vno;
int length;
@Override
public int compareTo(NodeType s) {
return length - s.length;
}
}
public static void main(String[] args) {
PriorityQueue<NodeType> queue = new PriorityQueue<>();
boolean[][] vis = new boolean[n][1 << n];
queue.offer(new NodeType(){{vno = 0; length = 0;}});
while (!queue.isEmpty()) {
NodeType cur = queue.poll();
if (cur.length > bestlen) {
break;
}
if (cur.vno == n - 1) {
bestlen = cur.length;
bestcount++;
continue;
}
if (vis[cur.vno][1 << cur.vno]) {
continue;
}
vis[cur.vno][1 << cur.vno] = true;
for (int i = 0; i < n; i++) {
if (A[cur.vno][i] != INF && !vis[i][1 << i]) {
queue.offer(new NodeType(){{vno = i; length = cur.length + A[cur.vno][i];}});
}
}
}
System.out.println(bestlen);
System.out.println(bestcount);
}
}