# poj 2075(prim 算法)

。。。小心啊写成“%1.f”一直出不来= =

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define MAXN 1000
#define INF 1000000000
using namespace std;
string data[MAXN];
float grid[MAXN][MAXN],cable;//cable is the maxi

bool comp(string a,string b)
{
int len_a=a.length(),len_b=b.length();
if(len_a!=len_b) return false;
for(int i=0;i<len_a;i++)
{
if(a[i]!=b[i]) return false;
}
return true;
}
int find_loc(string a,int n)
{
for(int i=1;i<=n;i++)
{
if(1==operator==(a,data[i]))
return i;
}
}
float ans;
void prim(int n)
{

int close[MAXN],i,u,num=1,merge;
float lowcost[MAXN],min_dis;
for(i=1;i<=n;i++)
{
lowcost[i]=INF,close[i]=0;
}
u=1;ans=0;close[1]=-1;
while(1)
{
if(num==n)
break;
min_dis=INF;
for(u =1;u<=n;u++)//多加了一成循环在【u】中找
{
if(close[u]==-1)
{
for(i=1;i<=n;i++)
{

if(close[i]!=-1&&grid[u][i]+1.0>1e-8)//判断是否有边
{

double tmp=grid[u][i];
if(tmp<lowcost[i])
lowcost[i]=tmp;
if(lowcost[i]<min_dis)
{
merge=i;
min_dis=lowcost[i];
}
}
}

}
}

ans+=min_dis;close[merge]=-1;
num++;
}
}
int main()
{
freopen("in.txt","r",stdin);
int n,m,i,a,b;
string x,y;
float dis;
while(scanf("%f",&cable)!=EOF)
{
scanf("%d",&n);
getchar();
for(i=1;i<=n;i++)
getline(cin,data[i]);
scanf("%d",&m);
for(i=1;i<=n;i++)     //用memset 的效果一样
for(int j=1;j<=n;j++)
grid[i][j]=-1.0;

for(i=1;i<=m;i++)
{
getchar();
getline(cin,x,' ');//c++对getline不接受，会ce
getline(cin,y,' ');
scanf("%f",&dis);
a = find_loc(x,n); b = find_loc(y,n);

grid[a][b]=grid[b][a]=dis;
}

prim(n);

if(ans>cable) printf("Not enough cable\n");
else printf("Need %.1f miles of cable\n",ans);//。。。小心啊写成“%1.f”一直出不来= =
}
return 0;
}


• 本文已收录于以下专栏：

## poj2075Tangled in Cables (最小生成树之prim)

Problem Description You are the owner of SmallCableCo and have purchased the franchise rights for a...

## POJ 2075 Tangled in Cables (kruskal算法 MST + map)

POJ 2075 Tangled in Cables (kruskal算法 MST + map)

## POJ 2075 Tangled in Cables(Kruskal算法)

Tangled in Cables Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 4014 ...

## poj1258prim算法

/*poj 1258 *题意：有若干个农场，现需要将各个农场用光纤连接起来，各个农场之间连接的光纤长度也许不同， *要求求出使得将所有农场连接起来的最短光线长度 *算法分析：使用矩阵将各个农...

## POJ 1251 Jungle Roads (最小生成树 Prim普里姆算法)

#include #define INF (1 << 31 - 1) #define MAX 27 int numOfVillages; int costMatrix[MAX][MAX];//u...

## poj1287 Networking 最小生成树模板题。prim+kruskal算法AC

You are assigned to design network connections between certain points in a wide area. You are given ...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)