最小生成树
未优化Prim和Kruscal 自用模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import java.io.*; import java.util.*; public class Main { static int[]pre; public static void main(String[] args) { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); while(sc.hasNext()){ int n=sc.nextInt(); int k=sc.nextInt(); pre=new int[n+1]; for(int i=0;i<=n;i++)pre[i]=i; ArrayList<Line>list=new ArrayList<Line>(); for(int i=1;i<=k;i++){ list.add(new Line(sc.nextInt(),sc.nextInt(),sc.nextInt())); } Collections.sort(list); int sum=0; for(int i=0;i<list.size();i++){ Line temp=list.get(i); if(find(temp.x)!=find(temp.y)){ sum+=temp.length; union(temp.x,temp.y); } } pw.println(sum); pw.flush(); } } static int find(int x){ if(x==pre[x])return x; else{ int root=find(pre[x]); return pre[x]=root; } } static void union(int a,int b){ int fa=find(a); int fb=find(b); if(fa!=fb){ pre[fa]=fb; } } } class Line implements Comparable<Line>{ int x,y; int length; Line(int x,int y,int length){ this.x=x; this.y=y; this.length=length; } public int compareTo(Line a) { if(this.length<a.length)return -1; if(this.length>a.length)return 1; return 0; } }
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); while(sc.hasNext()){ int n=sc.nextInt(); int[][]maze=new int[n][n]; int[]lowcost=new int[n]; boolean[]mst=new boolean[n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ maze[i][j]=sc.nextInt(); } } mst[0]=true; for(int i=1;i<n;i++){ lowcost[i]=maze[0][i]; } int index=-1; int sum=0; for(int i=1;i<n;i++){ int min=Integer.MAX_VALUE; for(int j=0;j<n;j++){ if(!mst[j]&&lowcost[j]<min){ min=lowcost[j]; index=j; } } mst[index]=true; sum+=min; for(int j=0;j<n;j++){ if(!mst[j]&&maze[index][j]<lowcost[j]){ lowcost[j]=maze[index][j]; } } } pw.println(sum); pw.flush(); } } }
|