NYOJ 38 wiring question _ (solution 2 Prim algorithm), nyojprim
Time Limit: 1000 MS | memory limit: 65535 KB difficulty: 4
-
Description
-
Nanyang institute of technology needs to transform the power line. The principal now asks the designer to design a wiring method which must meet the following requirements:
1. Power up all the buildings.
2. Minimum Cost of wires used
-
Input
-
The first line is an integer n, indicating that there are n groups of test data. (N <5)
The first line of each group of test data is two integers v, e.
V indicates the total number of school buildings (v <= 500)
In the subsequent line e, each line has three integers a, B, and c, which indicate that the cost of laying a line between a and B is c (c <= 100 ). (If no cost is specified for the two buildings, it indicates that the direct connection between the two buildings is too costly or impossible)
In the next line, there is a v integer, in which the I number represents the cost required to connect the wiring from building I to the external power supply facilities. (0 <e <v * (v-1)/2)
(The building number starts from 1). Due to security issues, you can only select one building to connect to the external power supply device.
There is at least one solution for data assurance to meet the requirements.
-
Output
-
Each group of test data outputs a positive integer, indicating the minimum cost of laying a line that meets the requirements of the principal.
-
Sample Input
-
14 61 2 102 3 103 1 101 4 12 4 13 4 11 3 5 6
-
Sample output
-
4
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <limits.h>#include <malloc.h>using namespace std;int sum;void Prim(int **node, int v){sum=0;int i,j,k,min;int *minCost=(int *)malloc(sizeof(int)*v);minCost[0]=0;for(i=1;i<v;i++)minCost[i]=node[0][i];for(i=1;i<v;i++){min=INT_MAX;for(j=1,k=1;j<v;j++){if(minCost[j] && minCost[j]<min){min=minCost[j];k=j;}}sum+=minCost[k];minCost[k]=0;for(j=1;j<v;j++){if(minCost[j] && minCost[j]>node[k][j]){minCost[j]=node[k][j];}}}}int main(){int n,v,e,i,j,k,l;scanf("%d",&n);while(n--){scanf("%d%d",&v,&e);int **node=(int **)malloc(sizeof(int*)*v); for(i=0;i<v;i++)node[i]=(int *)malloc(sizeof(int)*v);for(i=0;i<v;i++)for(j=0; j<v; j++)node[i][j]=INT_MAX;for(l=0;l<e;l++){scanf("%d%d%d",&i,&j,&k);node[i-1][j-1]=node[j-1][i-1]=k;}Prim(node, v);int *av=(int *)malloc(sizeof(int)*v);for(i=0;i<v;i++)scanf("%d",&av[i]);sort(av,av+v);printf("%d\n",sum+av[0]);}return 0;}