最近在复习以前数据结构的知识,找了一些练习题做做。最短路径和最小生成树和思想有类似的地方,基本都是贪心算法。
直接上代码吧,有不合适的地方希望大家指正。多谢!
typedef struct
{
int distance;
std::list<int> path;
} PATH;
//single point,
void ShortestPath(int p[][6], int size, std::vector<PATH > vexPath)
{
int i=0, j=0;
std::set<int> setA;
std::set<int> setB;
std::set<int>::iterator it;
for( i=1; i<size; i++)
{
setB.insert(i);
if(p[0][i]!=INT_MAX)
{
PATH temp;
temp.path.push_back(0);
temp.path.push_back(i);
temp.distance=p[0][i];
vexPath[i]=temp;
}
}
int index=0;
for( i=1; i< size; i++)
{
int temp=INT_MAX;
//get the shortest path from setA-setB
for(it=setB.begin(); it!= setB.end(); it++)
{
if(temp>vexPath[*it].distance)
{
temp=vexPath[*it].distance;
index=*it;
}
}
if(setB.find(index) !=setB.end() && temp<INT_MAX) setA.insert(index);
cout<<endl<<"select the lowest path, target node is :"<<index<<"and length is"<<temp<<endl;
setB.erase(index);
for(it=setB.begin(); it!= setB.end(); it++)
{
int k = *it;
if((p[index][k]!=INT_MAX) && vexPath[k].distance>vexPath[index].distance+p[index][k])
{
cout<<"update distance:INT_MAX->"<<k<<","<<vexPath[k].distance<<" with value :"<<vexPath[index].distance+p[index][k]<<endl;
vexPath[k].distance=vexPath[index].distance+p[index][k];
vexPath[k].path=vexPath[index].path;
vexPath[k].path.push_back(k);
}
}
std::list<int>::iterator it1 = (vexPath[index]).path.begin();
cout<<"After move node to setA:"<<index<<"path is:";
if(it1!=vexPath[index].path.end()) cout<<*(it1);
it1++;
for(it1; it1!=vexPath[index].path.end();it1++)
{
cout<<"->"<<*(it1);
}
cout<<endl;
}
}
//main function content
int arrayTest[6][6]={ {INT_MAX,50,10,INT_MAX,30,100},
{INT_MAX,INT_MAX,5,INT_MAX,INT_MAX,INT_MAX},
{INT_MAX,INT_MAX,INT_MAX,50,INT_MAX,INT_MAX},
{INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX,10},
{INT_MAX,INT_MAX,INT_MAX,20,INT_MAX,60},
{INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX,INT_MAX} };
std::vector<PATH > vexPath;
for(int i=0; i<6; i++)
{
PATH temp;
temp.distance=INT_MAX;
vexPath.push_back(temp);
}
ShortestPath(arrayTest, 6, vexPath);