POJ 1258
Prim算法:
-
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public classMain { static final int MAXN = 105; static final int MAXM = 20005; static final int MOD = 10000; static final int INF = 1000000000; static final double EPS = 1E-6; int n, q, a, b; int[][] g = new int[MAXN][MAXN]; boolean[] vis = new boolean[MAXN]; int[] dis = new int[MAXN]; void init() { } int Prim() { for (int i = 1; i <= n; i++) { vis[i] = false; dis[i] = INF; } dis[1] = 0; int sum = 0; for (int i = 1; i <= n; i++) { int k = -1; for (int j = 1; j <= n; j++) { if (vis[j] == false && (k == -1 || dis[j] < dis[k])) k = j; } sum += dis[k]; vis[k] = true; for (int j = 1; j <= n; j++) { if (vis[j] == false && g[k][j] < dis[j]) dis[j] = g[k][j]; } } return sum; } void run() { while (cin.hasNext()) { n = cin.nextInt(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = cin.nextInt(); } } System.out.println(Prim()); } } public static void main(String[] args) { Main solved = new Main(); solved.run(); } Scanner cin = new Scanner(new BufferedInputStream(System.in)); }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Kruskal算法:
-
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public classMain { static final int MAXN = 105; static final int MAXM = 5005; static final int MOD = 10000; static final int INF = 1000000000; static final double EPS = 1E-6; int n, es, x; int[] f = new int[MAXN]; Edge[] edge = new Edge[MAXM]; void init() { es = 0; for (int i = 1; i <= n; i++) f[i] = i; } int find(int x) { if (x != f[x]) f[x] = find(f[x]); return f[x]; } boolean Union(int x, int y) { x = find(x); y = find(y); if (x == y) return false; f[x] = y; return true; } int Kruskal() { int ans, j; ans = j = 0; for (int i = 0; i < es && j < n - 1; i++) { if (Union(edge[i].u, edge[i].v) == false) continue; ans += edge[i].w; j++; } return ans; } void run() { while (cin.hasNext()) { n = cin.nextInt(); init(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { x = cin.nextInt(); if (i < j) { edge[es++] = new Edge(i, j, x); } } } Arrays.sort(edge, 0, es); System.out.println(Kruskal()); } } public static void main(String[] args) { Main solved = new Main(); solved.run(); } Scanner cin = new Scanner(new BufferedInputStream(System.in)); } classEdge implements Comparable<Edge> { int u, v, w; Edge() {} Edge(int u, int v, int w) { this.u = u; this.v = v; this.w = w; } public int compareTo(Edge e) { return this.w - e.w; } }
////////////////////////////////////////////////////////////////////////////////
两者用的都是贪心,生成树不唯一。
注意Java的比较函数的写法。