poj1251最小生成树(kruskal算法)

来源:互联网 发布:微信淘宝客赚钱吗 编辑:程序博客网 时间:2024/05/16 02:56
#include <iostream>using namespace std;typedef struct//顶点信息{    char data;    int jihe;}VEX;typedef struct{    char vexh,vext;//边的顶点和终点    int weight;    int flag;}EDGE;VEX t[1000];EDGE e[1000];void Kruskal(int n,int m){    int i,j,k,min,sum=0,jun;    i=1;    while(i<n)    {        min=9999999;        for(j=0;j<m;j++)        {            if(e[j].weight<min&&e[j].flag==0)            {                min=e[j].weight;                k=j;            }        }        if(t[e[k].vexh-65].jihe!=t[e[k].vext-65].jihe)        {            e[k].flag=1;            jun=t[e[k].vext-65].jihe;            for(j=0;j<n;j++)            {                if(t[j].jihe==jun)                    t[j].jihe=t[e[k].vexh-65].jihe;            }            i++;        }       else       e[k].flag=2;    }    for(i=0;i<m;i++)    if(e[i].flag==1)    sum+=e[i].weight;    cout<<sum<<endl;}int main(){    int k,i,j,m,n;    while(cin>>k)    {        if(k==0)    break;        m=0;        for(i=0;i<k-1;i++)        {            cin>>t[i].data;            cin>>n;            t[i].jihe=i;            for(j=1;j<=n;j++)            {                e[m].vexh=t[i].data;                e[m].flag=0;                cin>>e[m].vext;cin>>e[m].weight;                m++;            }        }        t[i].jihe=i;        Kruskal(k,m);    }    return 0;}

kruskal算法+并查集

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int max_ve=1005,max_ed=15005;
int n,i;
struct node
{
    int par,ans;
}vertex[max_ve];
struct Edge
{
    int u,v,weight;
}edge[max_ed];
int cmp(const void *a,const void *b)
{
    return (*(Edge*)a).weight-(*(Edge*)b).weight;
}
int find(int j)
{
    if(vertex[j].par!=j)
    {
        vertex[j].par=find(vertex[j].par);
    }
    return vertex[j].par;
}
bool union_set(int s,int t)
{
    int os=find(s),ot=find(t);
    if(os==ot)
        return false;
    if(vertex[os].ans>vertex[ot].ans)
        vertex[ot].par=os;
    else
        vertex[os].par=ot;
    if(vertex[os].ans==vertex[ot].ans)
        vertex[ot].ans++;
    return true;
}
int main()
{
    int sum,ct,m,w,j;
    while(cin>>n&&n)
    {
        for(i=1;i<=n;i++)
        {
            vertex[i].par=i;vertex[i].ans=0;
        }
        char ch;
        j=0;
        for(i=1;i<n;i++)
        {
            cin>>ch>>m;
            while(m--)
            {
                cin>>ch>>w;
                edge[j].u=i;edge[j].v=ch-'A'+1;
                edge[j].weight=w;
                j++;
            }
        }
        qsort(edge,j,sizeof(edge[0]),cmp);
        sum=0;ct=0;
        for(i=0;i<j&&ct<n-1;i++)
        {
            if(union_set(edge[i].u,edge[i].v))
            {
                ct++;
                sum+=edge[i].weight;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

原创粉丝点击