标签:style blog color io 数据 for 问题 div
思路:刚学的最小生成树,顺便找个题目做一下~,普里姆算法轻松ac,没难度。。下次用kruskal算法试下
附上ac码:
#include <stdio.h> #include <string.h> int e[501][501];//储存地图 int h[501]; int mintree; int v,l; int prime()//普里姆算法 { int i,j; int book[501];//判断回路用的,book为1的表示已经加入树节点的楼 int temp; int count=0;//表示加入树节点的数量 int dis[501];//更新数组,作为辅助用 int sum = 0;//最小路径 int flag; memset(book,0,sizeof(book)); book[1] = 1; count++; for(i = 1; i<=v;i++) { dis[i] = e[1][i]; } while(count<v) { temp = 99999; for(j = 1;j<=v;j++) { if(book[j]==0&&dis[j]<temp) { temp = dis[j]; flag = j; } } book[flag] = 1; count++; sum +=dis[flag]; for(j=1;j<=v;j++) { if(book[j]==0&&dis[j]>e[flag][j]) dis[j] = e[flag][j]; } } mintree = sum; return 0 ; } int main() { //freopen("data.txt","r",stdin); mintree = 99999;//最后输出结果 int minl;//外界接电需要的钱 int num; int i,j,value;//临时变量 scanf("%d",&num); while(num--) { minl = 99999; scanf("%d %d",&v,&l); //初始化地图 for(i =1;i<=v;i++) { for(j =1;j<=v;j++) { if(i==j) e[i][j] = 0; else e[i][j] = 99999; } } //读入数据 for(int k = 1;k<=l;k++) { scanf("%d %d %d",&i,&j,&value); e[i][j] = value; e[j][i] = value; } //找出外界接电的最小值 for(i =1;i<=v;i++) { scanf("%d",h+i); minl = minl>h[i]?h[i]:minl; } prime(); printf("%d\n",mintree+minl); } return 0; }
标签:style blog color io 数据 for 问题 div
原文地址:http://www.cnblogs.com/ltwy/p/3907053.html