- 20/5/05
- 256
- 93
Mã:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GTS2_Console
{
class Program
{
const int MAX = 100;
public struct Graph
{
public int[,] A;
public int n;
public int p;
};
static Graph g;
public static int[] Tour;
public static int[] Check;
public static void LoadFile()
{
System.String s = null;
string[] token;
StreamReader myfile = null;
try
{
myfile = File.OpenText(@"d:\new.txt");
s = myfile.ReadLine();
token = s.Split();
g.n = token.Length;
g.A = new int[g.n, g.n];
Tour = new int[MAX];
Check = new int[MAX];
for (int i = 0; i < g.n; i++)
{
s = myfile.ReadLine();
token = s.Split();
for (int j = 0; j < g.n; j++)
g.A[i, j] = int.Parse(token[j]);
}
}
catch (Exception exc)
{
Console.Write("Khong mo file duoc!");
}
finally
{
if (myfile != null)
{
myfile.Close();
}
}
}
public static int TimDinhChiPhiThapNhat(int v)
{
int costmin = MAX; //= MAX - INT;
int vtmin = -1;
for (int i = 0; i < g.n; i++)
{
if (i != v && Check[i] == 0)
if (g.A[v, i] < costmin)
{
costmin = g.A[v, i];
vtmin = i;
}
}
return vtmin;
}
public static int GTS_1(int u)
{
Check[u] = 1;
int k = 0;
int v = u;
int w = 0;
Tour[k++] = u;
int cost = 0;
do
{
w = TimDinhChiPhiThapNhat(v);
Tour[k++] = w;
cost += g.A[v, w];
v = w;
Check[w] = 1;
} while (k < g.n);
Tour[k] = u;
cost += g.A[v, u];
return cost;
}
public static void GTS_2()
{
int costmin = MAX, umin = 0;
int cost1;
Console.Write("Nhap hai thanh pho tuong ung: ");
g.p = int.Parse(Console.ReadLine());
for (int i = 0; i < g.p; i++)
{
cost1 = GTS_1(i);
if (cost1 < costmin)
{
costmin = cost1;
//cost1 ++;
umin = i;
}
}
cost1 = GTS_1(umin);
Console.WriteLine("Hanh trinh cua dinh: " + "\n");
for (int j = 0; j < g.n; j++)
{
Console.Write(Tour[umin] + " ");
}
Console.WriteLine("Chi phi thap nhat la: " + costmin + "\n");
}
public static void Output()
{
for (int i = 0; i < g.n; i++)
{
for (int j = 0; j < g.n; j++)
Console.Write(g.A[i, j] + " ");
Console.WriteLine("");
}
}
static void Main(string[] args)
{
LoadFile();
Output();
Console.WriteLine("");
//Console.ReadLine();
/*
int u;
Console.Write("Moi nhap diem xuat phat (0->4): ");
u = int.Parse(Console.ReadLine());
Console.Write("Chi phi thap nhat la: " + GTS_1(u));
Console.WriteLine("");
*/
GTS_2();
}
}
}
Ở hàm GTS2, khi mình gọi GTS1 thì lại bị lỗi, mọi người giúp mình với
