Xin chào các bác, em đang làm bài tập về thuật toán Prim , em đã làm xong nhưng mỗi lần chạy lại bị bao lỗi:
Unhandled exception at 0x7784e42e (msvcr100d.dll) in Prim.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Mong các bác giúp em với. Em chỉnh sửa trong 2 ngay rồi mà vẫn không khắc phục lỗi được.
Đây là đề bài:
Code:
Bài tập thực hành 3: Thuật toán Prim (Hạn nộp: thứ 4, 07/09/2011)
* Yêu cầu:
+Nhập: Đọc dữ liệu đơn đồ thị từ tập tin văn bản "DOTHI.txt"
- Dòng đầu cho biết số đỉnh của đồ thị
- Các dòng tiếp theo cho biết ma trận TRỌNG SỐ của đồ thị
+ Xuất: Xuất cây khung ngắn nhất của đồ thị dưới dạng liệt kê cạnh vào tập tin văn bản <MSSV>.txt
* Ví dụ:
+ Nhập: "DOTHI.txt"
3
0 1 2
1 0 3
2 3 0
+ Xuất: <MSSV>.txt
0 - 1, 0 - 2
Còn đây là code C++ của em:
Code:
// 1185065.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <stdio.h>
#define MAX 100
using namespace std;
struct DOTHI {
int soDinh;
int mtTrongSo[MAX][MAX];
};
struct CANH{
int v; //Dinh dau
int w; //Dinh cuoi
};
CANH T[MAX]; //Canh cua cay khung ngan nhat
int nT; //So canh cua cay khung T
int lblVertex[MAX];
int nLbl;
void DocDoThi();
void PrimAlg();
void XuatKQLenFile();
void DocDoThi(DOTHI &g,char *input )
{
FILE *f = fopen("input.txt","rt");
if (f==NULL)
{
printf("Khong doc duoc file\n");
fclose(f);
return;
}
fscanf(f,"%d",g.soDinh);
for(int v=0 ; v < g.soDinh ; v++)
for (int w =0 ; w < g.soDinh ; w++)
fscanf(f, "%d", &g.mtTrongSo[v][w]);
fclose(f);
}
void PrimAlg(DOTHI g)
{
//gan so canh cua cay khung nT ban dau la 0
nT=0;
//Khoi tao nhan cua cac dinh la chua xet(0)
for (int i = 0; i < g.soDinh ; i++)
lblVertex[i] = 0;
//Gan nhan da xet(1) cho dinh 0
lblVertex[0] = 1;
while (nT < g.soDinh - 1) //So Canh toi da cua cay khung
{
CANH canhMin ;
int nMinWeight = -1; //Chua co canh min
//Duyet cac dinh cuoi thoa dk chua xet
for(int i = 1 ; i < g.soDinh ; i++)
if(lblVertex[i] ==0)
{
for(int j=0 ; j < g.soDinh ; j++)
if(lblVertex[j] == 1 && g.mtTrongSo[j][i] > 0)
{
if (nMinWeight < 0 || g.mtTrongSo[j][i] < nMinWeight)
{
canhMin.v = j;
canhMin.w = i;
nMinWeight=g.mtTrongSo[i][j];
}
}
}
//Them canh CanhMin vao cay khung
T[nT] = canhMin;
nT++;
//Gan nhan da xet cho dinh cuoi
lblVertex[canhMin.w]=1;
}
cout << nT << endl;
}
void XuatKQLenFile( CANH T[],int nT, char *output)
{
FILE *f =
f = fopen("output.txt","rt"); //Mo file output.txt
//Kiem tra co mo duoc hay khong
if (f==NULL)
{
printf("Khong doc duoc file\n");
fclose(f);
return;
}
for(int i=0;i<nT;i++)
{
fprintf(f, "%d, %d\t" , T[i].v, T[i].w );
}
//Dong tap tin
fclose(f);
}
void main(){
DOTHI g;
DocDoThi(g, "input.txt");
PrimAlg(g);
XuatKQLenFile(T, nT, "output.txt");
}