kama53.prim算法
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
//初始化图
int[][] graph = new int[n+1][n+1];
for(int i=0;i<n+1;i++) {
Arrays.fill(graph[i], Integer.MAX_VALUE);
}
for(int i=0;i<m;i++) {
int x = scan.nextInt();
int y = scan.nextInt();
int val = scan.nextInt();
graph[x][y]=val;
graph[y][x]=val;
}
// for(int i=1;i<=n;i++) {
// for(int j=1;j<=n;j++) {
// System.out.print(graph[i][j]+" ");
// }
// System.out.println();
// }
//初始化min数组以及标记数组
int[] min = new int[n+1];
Arrays.fill(min, Integer.MAX_VALUE);
boolean[] isChoose = new boolean[n+1];
//遍历min数组
for(int k=1;k<=n;k++) {
//找到当前最小值,如果是第一次则会显示1节点
int cur=1;
int minV=Integer.MAX_VALUE;
for(int i=1;i<=n;i++) {
if(isChoose[i]==false&&min[i]<minV) {
minV=min[i];
cur=i;
}
}
//加入节点
isChoose[cur]=true;
//更新min数组
for(int j=1;j<=n;j++) {
if(isChoose[j]==false&&min[j]>graph[cur][j]) {
min[j]=graph[cur][j];
}
}
}
//遍历获取答案
int res=0;
for(int i=2;i<=n;i++) {
// System.out.print(min[i]+" ");
res=res+min[i];
}
System.out.println(res);
scan.close();
}
kama53.kruskal算法
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
//初始化边集合
int[][] edges = new int[m][3];
for(int i=0;i<m;i++) {
edges[i][0]=scan.nextInt();
edges[i][1]=scan.nextInt();
edges[i][2]=scan.nextInt();
}
// 创建优先队列,并定义比较器
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[2] - o2[2]; // 根据权重进行排序
}
});
// 将所有边加入优先队列
for (int[] edge : edges) {
pq.add(edge);
}
//遍历所有最小边,并进行查并集
int[] father = new int[n+1];
int count=0;
int sum=0;
init(father);
for(int i=0;i<m;i++) {
//查看最小边
int[] edge = pq.poll();
if(!join(father,edge[0],edge[1])) {
count++;
sum=sum+edge[2];
}
if(count==n-1) break;
}
System.out.println(sum);
scan.close();
}
/**
* 查找根节点,并进行路径压缩
* @param father
* @param x
* @param y
* @return
*/
public static int findFather(int[]father,int x) {
if(father[x]==x)return x;
else return father[x]=findFather(father,father[x]);
}
/**
* 初始化
* @param father
*/
public static void init(int[] father) {
for(int i=1;i<father.length;i++) {
father[i]=i;
}
}
/**
* 判断是否在一个集合中
* @param father
* @param x
* @param y
* @return
*/
public static boolean isSame(int[]father,int x,int y) {
int res1 = findFather(father,x);
int res2 = findFather(father,y);
if(res1==res2)return true;
return false;
}
public static boolean join(int[]father,int x,int y) {
int res1 = findFather(father,x);
int res2 = findFather(father,y);
if(res1==res2) {
return true;
}
father[res2]=res1; //把根节点连在一起
return false;
}