Kruscal算法1.5

http://poj.org/problem?id=2075

最小生成树,不过要判断是否存在最小生成树和价值是否达标

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 102
#include<map>
#define INF 1000000
using namespace std;
struct node
{
    int u;
    int v;
    double w;
    node()
    {
        w=1000000.0;
    }
} edge[500000];
int pre[10000];
int n,m;
double s;
bool cmp(const node&a,const node&b )
{
    return a.w<b.w;
}
int find(int x)
{
    return x==pre[x]?x:pre[x]=find(pre[x]);
}
void unions(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }
}
void createGraph()
{
    map<string,int>mp;
    memset(pre,0,sizeof(pre));
    for(int i=1; i<=n; i++)
    {
        string s;
        cin>>s;
        mp[s]=i;
    }
    int k;
    cin>>k;
    string a,b;
    double w;
    for(int i=1; i<=k; i++)
    {
        cin>>a>>b>>w;
        edge[++m].u=mp[a];
        edge[m].v=mp[b];
        edge[m].w=w;
    }
    for(int i=1; i<=n; i++)pre[i]=i;
}
double kruscal()
{
    double ans=0;
    int ans1=0;
    sort(edge+1,edge+m+1,cmp);
    for(int i=1; i<=m; i++)
    {
        if(find(edge[i].u)!=find(edge[i].v))
        {
            unions(edge[i].u,edge[i].v);
            ans1++;
            ans+=edge[i].w;

        }
    }
    if(ans1>=n-1&&ans<=s)return ans;
    return -1;
}
int main()
{
    cin>>s;
    cin>>n;
    createGraph();
    double a=kruscal();
    if(a>0)
    {
        cout<<"Need "<<a<<" miles of cable";
        return 0;
    }
    cout<<"Not enough cable";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/83216479