using System.Collections;
class EDGEComparer : IComparer
public int Compare(object x, object y)
if (((EDGE)x).weight > ((EDGE)y).weight) return 1;
if (((EDGE)x).weight < ((EDGE)y).weight) return -1;
public static void Main()
AdjencyMatrix g = new AdjencyMatrix();
static void PrintListEdges(EDGE []lstEdges) {
for (int i = 0; i < lstEdges.Length; i++) {
Console.WriteLine(String.Format("{0}-{1}: {2}", lstEdges[i].v, lstEdges[i].w, lstEdges[i].weight));
static EDGE[] SortListEdge(AdjencyMatrix g) {
EDGE []lstEdges = InitListEdge(g);
EDGEComparer eC = new EDGEComparer();
Array.Sort(lstEdges, eC);
static EDGE[] InitListEdge(AdjencyMatrix g) {
EDGE []lstEdges = new EDGE[g.n * (g.n - 1)];
for (int i = 0; i < g.n; i++) {
for (int j = i; j < g.n; j++) {
lstEdges[nEdgesCount] = edge;
EDGE []result = new EDGE[nEdgesCount];
for (int i = 0; i < nEdgesCount; i++) {
static int Find(Subset[] subsets, int i) {
if (subsets[i].parent != i) {
subsets[i].parent = Find(subsets, subsets[i].parent);
return subsets[i].parent;
static void Union(Subset[] subsets, int x, int y) {
int xroot = Find(subsets, x);
int yroot = Find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
} else if (subsets[xroot].rank > subsets[yroot].rank) {
subsets[yroot].parent = xroot;
subsets[yroot].parent = xroot;
static bool IsCircle(Subset []subsets, EDGE currentEdge) {
int x = Find(subsets, currentEdge.v);
int y = Find(subsets, currentEdge.w);
static void kruskal(AdjencyMatrix g) {
EDGE []T = new EDGE[g.n - 1];
Subset[] subsets = new Subset[g.n];
EDGE []lstEdges = SortListEdge(g);
int nEdgesCount = lstEdges.Length;
for (int i = 0; i < g.n; i++) {
Subset subset = new Subset();
if (eMinIndex < nEdgesCount) {
if (IsCircle(subsets, lstEdges[eMinIndex]) == false) {
T[nT++] = lstEdges[eMinIndex];
Console.WriteLine("Tap canh cua cay khung:");
for (int i=0; i < T.Length; i++) {
totalWeight += T[i].weight;
Console.WriteLine(String.Format("{0}-{1}: {2}", T[i].v, T[i].w, T[i].weight));
Console.WriteLine(String.Format("Tong so cua cay khung nho nhat: {0}", totalWeight));
static void prim(AdjencyMatrix g, int source) {
EDGE []T = new EDGE[g.n - 1];
bool []marked = new bool[g.n];
for (int i = 0; i < g.n; i++) {
EDGE edgeMin = new EDGE();
for (int w = 0; w < g.n; w++) {
if (marked[w] == false) {
for (int v = 0; v < g.n; v++) {
if (marked[v] == true && g.a[v, w] !=0) {
if (nMinWeight == -1 || g.a[v, w] < nMinWeight) {
edgeMin.weight = g.a[v, w];
marked[edgeMin.w] = true;
Console.WriteLine("Tap canh cua cay khung:");
for (int i=0; i < T.Length; i++) {
totalWeight += T[i].weight;
Console.WriteLine(String.Format("{0}-{1}: {2}", T[i].v, T[i].w, T[i].weight));
Console.WriteLine(String.Format("Tong so cua cay khung nho nhat: {0}", totalWeight));