hdu 1102
题意:已知N点间的距离,若有M条路已建(a,b之间是通路),求还需建多长的路,输出路的最小值。
对于M条路已建(a,b之间是通路)这一条件,只需令f[a][b] = f[b][a] = 0;
解决掉这个问题,就按prim 模板即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #define INf 0x7ffffff 4 int n,m; 5 int f[105][105],vis[105],dis[105]; 6 int prim() 7 { 8 int i,j,k,t,r; 9 for(i = 1;i <= n;i ++) 10 { 11 dis[i] = INf; 12 } 13 dis[1] =0; 14 for(i = 1;i <= n;i ++) 15 { 16 t = INf; 17 for(j = 1;j <= n;j ++) 18 { 19 if(!vis[j] && dis[j]<t) 20 { 21 t = dis[j]; 22 k = j; 23 } 24 } 25 vis[k] = 1; 26 for(j = 1;j <= n;j ++) 27 { 28 if(dis[j] > f[k][j] && !vis[j]) 29 dis[j] = f[k][j]; 30 } 31 } 32 r = 0; 33 for(i = 1;i <= n;i ++) 34 { 35 r += dis[i]; 36 } 37 return r; 38 } 39 int main() 40 { 41 int i,j,k,a,b; 42 while(~scanf("%d",&n)) 43 { 44 memset(vis,0,sizeof(vis)); 45 46 for(i = 1;i <= n;i ++) 47 { 48 for(j = 1;j <= n;j ++) 49 { 50 scanf("%d",&f[i][j]); 51 } 52 } 53 scanf("%d",&m); 54 while(m --) 55 { 56 scanf("%d %d",&a,&b); 57 f[a][b] = 0; 58 f[b][a] = 0; 59 } 60 k = prim(); 61 printf("%d ",k); 62 } 63 return 0; 64 }