贪心算法 Dijkstra和Prim

贪心算法

#ifndef GXF3_H_INCLUDED
#define GXF3_H_INCLUDED

#include<iostream>


void Dijkstra(int n,int v,int dist[],int prev[],int c[6][6])
{
    int maxint=999;
    bool s[maxint];
    for(int i=1;i<=n;i++)
    {
        dist[i]=c[v][i];
        s[i]=false;
        if(dist[i]==maxint)
            prev[i]=0;
            else
            prev[i]=v;
    }
    dist[v]=0;s[v]=true;
    for(int i=1;i<n;i++)
    {
        int temp=maxint;
        int u=v;
        for(int j=1;j<=n;j++)
            if((!s[j])&&(dist[j]<temp))
        {
            u=j;
            temp=dist[j];

        }
        s[u]=true;
        for(int j=1;j<=n;j++)
        {
            if((!s[j])&&(c[u][j]<maxint))
            {
                int newdist=dist[u]+c[u][j];
                if(newdist<dist[j])
                {
                    dist[j]=newdist;
                    prev[j]=u;
                }
            }
    }
}
}
template<class Type>
void Prim(int n,Type c[7][7])
{

    int maxint=99;
    Type lowcost[maxint];
    int closest[maxint];
    bool s[maxint];
    s[1]=true;
    for(int i=2;i<=n;i++)
    {
        lowcost[i]=c[1][i];
        closest[i]=1;
        s[i]=false;

    }
    for(int i=1;i<n;i++)
    {
        Type min=999;
        int j=1;
        for(int k=2;k<=n;k++)
        {
            if((lowcost[k]<min)&&(!s[k]))
            {
                min=lowcost[k];
                j=k;

            }
        }
                  std::cout<<j<<"-"<<closest[j]<<std::endl;
            s[j]=true;
            for(int k=2;k<=n;k++)
            {
                if((c[j][k]<lowcost[k])&&(!s[k]))
                {
                    lowcost[k]=c[j][k];
                    closest[k]=j;
                }
            }
    }
}
#endif // GXF3_H_INCLUDED

using namespace std;
int main()
{

    int dist[20];
    int prev[20];

    int maxint=999;
    int  x=5;
    int c[6][6]={
        {0,0,0,0,0,0},
    {0,0,10,999,30,100},
    {0,999,0,50,999,999},
    {0,999,999,0,999,10},
    {0,999,999,20,0,60},
    {0,999,999,999,999,0},
    };
     cout<<"Dijkstra:"<<endl;
    Dijkstra(x,1,dist,prev,c);
    for(int i=1;i<=5;i++)
    {
        cout<<i<<" "<<prev[i];
        int temp=prev[i];
        while(temp!=1)
        {
            temp=prev[temp];
            cout<<temp<<" ";
        }

        cout<<":"<<dist[i]<<endl;

    }


cout<<"Prim:"<<endl;
    int  n = 6;
    int  m[7][7]={
{0,0,0,0,0,0,0},
{0,0,6,3,5,99,99},
{0,6,0,5,99,3,99},
{0,1,5,0,5,6,4},
{0,5,99,5,0,99,2},
{0,99,3,6,99,0,6},
{0,99,99,4,2,6,0}
};
    Prim(n,m);

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值