我想在 C++ 中实现 Kriskal 的算法,但是......
DAA.exe 中 0x0127160d 处未处理的异常:0xC0000005:访问冲突读取位置 0xdd2021d4。
它在 getRoot 函数的这一行停止:
而(城市[根].prev!= NO_PARENT)
我认为问题在于城市数组中的数据。当我打印数组中的所有数据时,这不是我想要的。城市的名称是这样的“════════════════¤¤¤¤ллллллю■ю■”和数字(int) - 像这样(-842150451)。以下是完整代码。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define NO_PARENT -1
struct city {
char name[11];
int prev;
};
struct path {
unsigned i, j, price;
};
bool comparsion(path p1, path p2) {
return p1.price > p2.price;
}
int getRoot(city *cities, int cityNumber) {
int root = cityNumber, tmp;
while(cities[root].prev != NO_PARENT)
root = cities[root].prev;
while(cityNumber != root) {
tmp = cityNumber;
cityNumber = cities[cityNumber].prev;
cities[tmp].prev = root;
}
return root;
}
bool isListed(city *cities, int n, char cityName[]) {
for(int i = 0; i < n; i++)
if(strcmp(cities[i].name, cityName))
return true;
return false;
}
int getCityNumber(city *cities, int n, char cityName[]) {
for(int i = 0; i < n; i++)
if(strcmp(cities[i].name, cityName))
return i;
return NO_PARENT;
}
int minPrice(city *cities, path *paths, int cityCount, int pathCount) {
unsigned minPrice = 0;
// sort paths by price
std::sort(paths, &paths[pathCount-1], comparsion);
for(int k = 0; k < pathCount; k++) {
printf("path: %d - %d\n", paths[k].i, paths[k].j);
int c1 = getRoot(cities, paths[k].i), c2 = getRoot(cities, paths[k].j);
if(c1 != c2) {
minPrice += paths[k].price;
cities[c2].prev = c1;
}
}
return minPrice;
}
int main() {
int n, m, k;
do {
scanf("%d %d %d", &n, &m, &k);
} while(n < 2 || n > 10001 || m < -1 || m > 100001 || k < -1 || k > 100001);
city* cities = (city*)malloc(n*sizeof(city));
path* paths = (path*)malloc((m + k)*sizeof(path));
int addCities = 0;
char city1[11], city2[11];
for(int i = 0; i < (m + k); i++) {
scanf("%s %s", city1, city2);
if(addCities < n && !isListed(cities, n, city1)) { // if city1 is not into cities
// add it
strcpy(cities[addCities].name, city1);
cities[addCities].prev = NO_PARENT;
addCities++;
}
paths[i].i = getCityNumber(cities, n, city1); // number of city1
if(addCities < n && !isListed(cities, n, city2)) { // if city2 is not into cities
// add it
strcpy(cities[addCities].name, city2);
cities[addCities].prev = NO_PARENT;
addCities++;
}
paths[i].j = getCityNumber(cities, n, city1); // number of city2
if(i >= m)
scanf("%d", &paths[i].price);
}
for(int i = 0; i < (m + k); i++)
printf("%s: %d\n", cities[i].name, cities[i].prev);
// Calculate min price
printf("%d ", minPrice(cities, paths, n, k + m));
system("pause");
return 0;
}