1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include<stdio.h> #include<time.h> #include<stdlib.h> #include<math.h> #define MaxSize (10000)
typedef struct City{ int id; int x, y; }CITY; typedef struct edges{ int s, e; double cost; }EDGE;
void CreateCityPos(CITY *& city, int n){ city = (CITY*)malloc(sizeof(CITY)* n); srand((unsigned)time(NULL)); for (int i = 0; i < n; ++i) { city[i].id = i + 1; city[i].x = rand() % 100; city[i].y = rand() % 100; } } void ShowCityPos(CITY*city, int n) { printf("\n各城市的编号及坐标:\n"); for (int i = 0; i < n; ++i) { printf("%d:[%d, %d]\n", city[i].id, city[i].x, city[i].y); } }
int Sum(int n) { int sum = 0; for (int i = 1; i <= n; ++i) sum += i; return sum; } double CityDist(const CITY*a, const CITY*b) { return sqrt(double((a->x - b->x)*(a->x - b->x) + (a->y - b->y)*(a->y - b->y))); } void CreateEdges(EDGE* & e, CITY* city, int n) { e = (EDGE*)malloc(sizeof(EDGE)*Sum(n - 1)); int cnt = 0; for (int i = 0; i < n; ++i) { for (int k = i + 1; k < n; ++k) { (e + cnt)->s = city[i].id; (e + cnt)->e = city[k].id; (e + cnt)->cost = CityDist(&city[i], &city[k]); ++cnt; } } } void ShowCityEdges(EDGE*edges, int n) { printf("\n各城市间的距离(城市1-城市2:边权值(距离))\n"); for (int i = 0; i < Sum(n-1); ++i) printf("%d-%d : %f\n", edges[i].s, edges[i].e, edges[i].cost); }
int cmp(const void*a, const void *b) { EDGE* aa, *bb; aa = (EDGE*)a; bb = (EDGE*)b; if ((aa->cost - bb->cost )> 0) return 1; else return -1; }
int v[MaxSize]; int getRoot(int a) { while (a != v[a]) a = v[a]; return a; } void KrusKal(EDGE* edges, int n) { int i; int e, a, b; double sum = 0.0; e = Sum(n - 1); for (i = 0; i < n; ++i) v[i] = i; printf("\n最小生成树的边及权值:\n"); for (i = 0; i < e; ++i) { a = getRoot(edges[i].s); b = getRoot(edges[i].e); if (a != b) { v[a] = b; printf("%d-%d: %f\n", edges[i].s, edges[i].e, edges[i].cost); sum += edges[i].cost; } } printf("\n生成树总权值sum =%f\n", sum); }
void solve(int n) { CITY*city; EDGE* edges; CreateCityPos(city, n); ShowCityPos(city, n); CreateEdges(edges, city, n); qsort(edges, Sum(n - 1), sizeof(EDGE), cmp); ShowCityEdges(edges, n); KrusKal(edges, n); } int main() { int n; printf("请输入n:"); scanf("%d", &n); if (n < 2) return 1; solve(n); return 0; }
|