贪心算法
#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
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;
}