好累啊。。好几天没写了,今天不知道怎么回事效率特别低,半个下午加一个晚上就一道。感觉写起来各种不顺和无从下手,其实用JAVA早写好了,后来又用C想用二叉堆来做的,各种不顺手。。最终放弃了,简单地用了个快排来代替堆了,用C也写了不少代码了,总感觉没有入门的样子。。郁闷,算了睡觉鸟,暂时先这样吧,这题其实就最基础的最小生成树,算法书上照搬过来的,功夫不到家真是悲剧,觉得应该多读些别人的优秀代码了
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Vertex
{
int index;
int key;
int parent;
};
int cmp2966(const void *p1, const void *p2)
{
struct Vertex *n1 = (struct Vertex *) p1;
struct Vertex *n2 = (struct Vertex *) p2;
return n1->key - n2->key;
}
void prim(struct Vertex *array, int a[500][500], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
array[i].key = 1024;
array[i].index = i;
array[i].parent = -1;
}
array[0].key = 0;
int size = n;
while (size)
{
struct Vertex min = array[0];
array[0] = array[size - 1];
array[size - 1] = min;
size--;
int index = min.index;
for (i = 0; i < n; i++)
{
if (a[index][i] != -1)
{
for (j = 0; j < size; j++)
{
if (array[j].index == i && a[index][i] < array[j].key)
{
array[j].key = a[index][i];
array[j].parent = index;
}
}
}
}
qsort(array, size, sizeof(array[0]), cmp2966);
}
}
int main()
{
int t, a[500][500];
scanf("%d", &t);
while (t--)
{
memset(a, -1, 500 * 500 * sizeof(int));
int n, e, i;
scanf("%d %d", &n, &e);
while (e--)
{
int aa, bb, kk;
scanf("%d %d %d", &aa, &bb, &kk);
a[aa][bb] = kk;
a[bb][aa] = kk;
}
struct Vertex *array = malloc(n * sizeof(struct Vertex));
prim(array, a, n);
int sum = 0;
for (i = 0; i < n; i++)
if (array[i].parent != -1)
sum += a[array[i].index][array[i].parent];
printf("%d\n", sum);
free(array);
}
return 0;
}
今天用O(V^2)时间界又写了Prim算法,用二叉堆有更好的时间界,但是C写太繁琐了,暂时作罢
#include<stdio.h>
#include<string.h>
int main()
{
int t, a[500][500], k[500], d[500], p[500];
scanf("%d", &t);
while (t--)
{
memset(k, 0, 500 * sizeof(int));
memset(p, -1, 500 * sizeof(int));
memset(a, -1, 500 * 500 * sizeof(int));
int n, e;
scanf("%d %d", &n, &e);
while (e--)
{
int a1, a2, a3;
scanf("%d %d %d", &a1, &a2, &a3);
a[a1][a2] = a3;
a[a2][a1] = a3;
}
int i, j, min, now = 0, next;
for (i = 0; i < 500; i++)
d[i] = 1024;
d[0] = 0;
for (i = 0; i < n; i++)
{
k[now] = 1;
min = 9999;
for (j = 0; j < n; j++)
{
if (a[now][j] != -1 && !k[j] && a[now][j] < d[j])
{
d[j] = a[now][j];
p[j] = now;
}
if (!k[j] && d[j] < min)
{
min = d[j];
next = j;
}
}
now = next;
}
int sum = 0;
for (i = 0; i < n; i++)
if (p[i] != -1)
sum += a[i][p[i]];
printf("%d\n", sum);
}
return 0;
}