Electrification Plan(最小生成树)
http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=50#problem/D
最小生成树模板,注意的是这里有k个发电站,它们不再需要连接其他的发电站,所以任何两个发电站之间的权值是0;
1 #include<stdio.h> 2 #include<string.h> 3 const int maxn = 110; 4 const int INF = 0x3f3f3f3f; 5 int map[maxn][maxn],power[maxn]; 6 int n,k; 7 8 void prim() 9 { 10 int dis[maxn],vis[maxn]; 11 int ans = 0; 12 memset(vis,0,sizeof(vis)); 13 for(int i = 1; i <= n; i++) 14 dis[i] = map[1][i]; 15 vis[1] = 1; 16 17 for(int i = 1; i <= n-1; i++) 18 { 19 int min = INF,pos; 20 21 for(int j = 1; j <= n; j++) 22 { 23 if(!vis[j] && dis[j] < min) 24 { 25 min = dis[j]; 26 pos = j; 27 } 28 } 29 vis[pos] = 1; 30 ans += min; 31 for(int j =1; j <= n; j++) 32 { 33 if(!vis[j] && dis[j] > map[pos][j]) 34 dis[j] = map[pos][j]; 35 } 36 } 37 printf("%d\n",ans); 38 } 39 40 int main() 41 { 42 scanf("%d %d",&n,&k); 43 44 /*for(int i = 1; i <= n; i++) 45 for(int j = 1; j <= n; j++) 46 { 47 if(i != j) 48 map[i][j] = INF; 49 else map[i][j] = 0; 50 }*/ 51 memset(power,0,sizeof(power)); 52 int x; 53 54 for(int i = 0; i < k; i++) 55 { 56 scanf("%d",&x); 57 power[x] = 1; 58 } 59 60 for(int i = 1; i <= n; i++) 61 { 62 for(int j = 1; j <= n; j++) 63 scanf("%d",&map[i][j]); 64 } 65 66 for(int i = 1; i <= n; i++) 67 { 68 for(int j = 1; j <= n; j++) 69 { 70 if(power[i] && power[j]) 71 map[i][j] = 0; 72 } 73 } 74 prim(); 75 return 0; 76 }