// Prim's Algorithm in C using a table with the best S vertex for // every T vertex. Adjacency lists are used for storing the // undirected graph. // See CSE 2320 Notes 15 #include #include // For getrusage() #include #include // Basic Definitions #define oo (1000000000) // Declarations int numVertices,numEdges; struct edge { int tail,head,weight; int next; // subscript of next edge with same tail }; typedef struct edge edgeType; edgeType *edgeTab; int *firstEdge; // Table indicating first edge for a tail float CPUtime() { struct rusage rusage; getrusage(RUSAGE_SELF,&rusage); return rusage.ru_utime.tv_sec+rusage.ru_utime.tv_usec/1000000.0 + rusage.ru_stime.tv_sec+rusage.ru_stime.tv_usec/1000000.0; } void read_input_file() { // Reads a file with a weighted, undirected graph and // stores as unordered adjacency lists. int tail,head,weight,i,j,workingEdges; // read number of nodes and edges scanf("%d %d",&numVertices,&numEdges); // Tables are allocated with space for inverses. firstEdge=(int*) malloc(numVertices*sizeof(int)); edgeTab=(edgeType*) malloc(2*numEdges*sizeof(edgeType)); if (!firstEdge || !edgeTab) { printf("edgeTab malloc failed %d\n",__LINE__); exit(0); } // Initially, all adjacency lists are empty for (i=0;inumVertices-1 || head<0 || head>numVertices-1 || weight<=0) { printf("Invalid input %d %d %d at %d\n",tail,head,weight,__LINE__); exit(0); } // Save input edge and insert in adjacency list edgeTab[workingEdges].tail=tail; edgeTab[workingEdges].head=head; edgeTab[workingEdges].weight=weight; edgeTab[workingEdges].next=firstEdge[tail]; firstEdge[tail]=workingEdges; workingEdges++; // Save inverse of input edge and insert in adjacency list edgeTab[workingEdges].tail=head; edgeTab[workingEdges].head=tail; edgeTab[workingEdges].weight=weight; edgeTab[workingEdges].next=firstEdge[head]; firstEdge[head]=workingEdges; workingEdges++; } } void prim() { typedef enum {s,t} stType; int i,j,MSTedgeCount=0,MSTweight=0,smallestWeight,smallestVertexNumber; stType *flag; int *Tweight,*bestSneighbor; flag=(stType*) malloc(numVertices*sizeof(stType)); Tweight=(int*) malloc(numVertices*sizeof(int)); bestSneighbor=(int*) malloc(numVertices*sizeof(int)); if (!flag || !Tweight || !bestSneighbor) { printf("malloc failed %d\n",__LINE__); exit(0); } // Vertex 0 starts in S. Other vertices start in T. flag[0]=s; for (i=1;i