#include <stdio.h>
#include <malloc.h>
#define MaxArcNum 1000000
#define MaxVerNum 100000
struct ArcNode {
int v1, v2, dist;
};
struct GraphStruct {
int arcnum, vexnum;
struct ArcNode a[MaxArcNum];
};
typedef struct GraphStruct* Graph;
int Parent[MaxVerNum];
int Deep[MaxVerNum];
Graph createGraph();
void inputData( Graph G );
int Kruskal( Graph G );
int findPar( int v );
void uniteTree( int v1, int v2 );
void QuickSort( struct ArcNode a[], int s, int f );
int Partition( struct ArcNode a[], int s, int f );
void swap( struct ArcNode* a, struct ArcNode* b );
int RandPartition( struct ArcNode a[], int s, int f );
int main( void ) {
int MinDistTree = 0;
Graph G = createGraph();
inputData( G );
MinDistTree = Kruskal( G );
printf("%d ", MinDistTree);
return 0;
}
Graph createGraph() {
Graph G = ( Graph )malloc( sizeof(struct GraphStruct) );
FILE* fp = fopen("kruskal1.txt", "r");
fscanf(fp, "%d %d", &G->vexnum, &G->arcnum);
return G;
}
void inputData( Graph G ) {
int i = 0;
int v1, v2, dist;
FILE* fp = fopen("kruskal2.txt", "r");
for( i = 0; i < G->arcnum; i++ ) {
fscanf(fp, "%d %d %d", &v1, &v2, &dist);
G->a[i].v1 = v1-1;
G->a[i].v2 = v2-1;
G->a[i].dist = dist;
}
}
int Kruskal( Graph G ) {
int v1, v2, dist = 0, nEdge = 0;
int i = 0;
QuickSort( G->a, 0, G->arcnum-1 );
// for( i = 0; i < G->arcnum; i++ ) {
// printf("%d %d %d\n", G->a[i].v1, G->a[i].v2, G->a[i].dist);
// }
for( i = 0; i < G->vexnum; i++ ) {
Parent[i] = i;
Deep[i] = 0;
}
for( i = 0; i < G->arcnum && nEdge < (G->vexnum)-1; i++ ) {
v1 = G->a[i].v1;
v2 = G->a[i].v2;
if( findPar(v1) != findPar(v2) ) {
uniteTree( v1, v2 );
dist += G->a[i].dist;
nEdge++;
}
}
if( nEdge < (G->vexnum)-1 ) { dist = -1; }
return dist;
}
int findPar( int v ) {
int p = Parent[v];
int lastP = v;
while( p!= lastP ) {
lastP = p;
p = Parent[lastP];
}
//压缩路径(搞得很牛逼样的)
Parent[v] = p;
return p;
}
void uniteTree( int v1, int v2 ) {
v1 = findPar( v1 );
v2 = findPar( v2 );
if( Deep[v1] < Deep[v2] ) {
Parent[v2] = v1;
}
else {
Parent[v1] = v2;
if( Deep[v1] < Deep[v2] ) { Deep[v2]++; }
}
}
void QuickSort( struct ArcNode a[], int s, int f ) {
if( s >= f ) { return; }
int m = 0;
while( f > s ) {
m = RandPartition( a, s, f );
QuickSort( a, s, m-1 );
s++;
}
}
int Partition( struct ArcNode a[], int s, int f ) {
int x = a[f].dist;
int i = s-1;
int j = s;
for( j = s; j <= f-1; j++ ) {
if( a[j].dist < x ) {
i++;
swap( &a[i], &a[j] );
}
}
i = i+1;
swap( &a[i], &a[f] );
return i;
}
void swap( struct ArcNode* a, struct ArcNode* b ) {
struct ArcNode c = *b;
(*b).dist = (*a).dist;
(*b).v1 = (*a).v1;
(*b).v2 = (*a).v2;
(*a).dist = c.dist;
(*a).v1 = c.v1;
(*a).v2 = c.v2;
}
int RandPartition( struct ArcNode a[], int s, int f ) {
int tmp = rand()%( f-s ) + s;
swap( &a[tmp], &a[f] );
return Partition( a, s, f );
}
待会写prim。。。
kruskal(并查集+快排)
最新推荐文章于 2022-07-05 01:08:50 发布