给一些地点名和地点之间路径,选出一些路是各地相通,求最短距离
最小生成树问题,可题目连数据范围都没写,写时候很纠结,没想到测试数据这么小
Kruskal解决
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstdio>
using namespace std;
struct Edge
{
int u,v;
double w;
};
struct PRE
{
int i;
string s;
};
int find(int x,PRE pre[])
{
if(x!=pre[x].i)
pre[x].i=find(pre[x].i,pre);
return pre[x].i;
}
void Union(int x,int y,PRE pre[])
{
int fx=find(x,pre);
int fy=find(y,pre);
pre[fx].i=fy;
}
int cmp(const void* p1,const void* p2)
{
Edge a=*(Edge*)p1;
Edge b=*(Edge*)p2;
if(a.w>b.w)
return 1;
else
return -1;
}
int main()
{
double total;
cin>>total;
int n;
cin>>n;
PRE* pre=new PRE[n];
for(int i=0; i<n; i++)
{
pre[i].i=i;
cin>>pre[i].s;
}
int v;
cin>>v;
Edge* edge=new Edge[v];
for(int i=0; i<v; i++)
{
string tmp;
cin>>tmp;
for(int j=0; j<n; j++)
if(tmp==pre[j].s)
{
edge[i].u=j;
break;
}
cin>>tmp;
for(int j=0; j<n; j++)
if(tmp==pre[j].s)
{
edge[i].v=j;
break;
}
cin>>edge[i].w;
}
qsort(edge,v,sizeof(Edge),cmp);
double sum=0.0;
int cnt=0;
for(int i=0; i<v; i++)
{
if(find(edge[i].u,pre)!=find(edge[i].v,pre))
{
sum+=edge[i].w;
Union(edge[i].u,edge[i].v,pre);
cnt++;
}
if(cnt==n-1)
break;
}
if(sum>total)
cout<<"Not enough cable"<<endl;
else
cout<<"Need "<<sum<<" miles of cable"<<endl;
delete [] pre;
delete [] edge;
}