2011年的最后一天

       今年是2011年12月31号,这一天不知道自己在想什么,只是有点累,生活不知道是怎么样子的?看过太多社会的悲惨事迹,心里素质已经加强了,不再像以前那样多愁善感,社会也许是不公的,但是唯有自己的努力才能改变自己的命运,加油吧。最近看了一下迪克斯特算法,这个写得还不错。总是想多看几遍,在计算机网络的路由选择协议采用的:

//迪克斯拉算法的实现
template <class T>
struct PathInfo
{
 T startV,endV;
 int cost;
};
template<class T>
int operator <=(const PathInfo<T>&a,const PathInfor<T>&b)//实现运算符<=重载,

{
 return a.cost<=b.cost;
}
//用优先序列实现最短路径算法
template<class T>
int Graph<T>::MinimumPath(const T&sVertex,const T&eVertex)
{
    PQueue<PathInfo<T>>PQ(MaxGraphSize);
 PathInfo<T>pathDate;
 Seqlist<T>L,adjL;
 SeqListIterator<T>adjLiter(adjL);
 T sv,ev;
 int mincost;
    pathData.startV=sVertex;
 pathData.endV=sVertex;
 pathData.cost=0;
 PQ.PQInsert(pathData);
 while(!PQ.PQEmpty())
 {
  pathData=pathData.endV;
  mincostpathData.cost;
  if(ev==eVertex) break;
  if(!FindVertex(L,ev))
  {
   L.Insert(ev);
   sv=ev;
   adjL=GetNeighbors(sv);
   adjLiter.SetList(adjL);
   for(adjLiter.Reset( );!adjLiter.EndOfList( ); adjLiter.Next( ))
   {  ev = adjLiter.Data( );           
      if (!FindVertex(L,ev))
      { pathData.startV = sv;
                 pathData.endV = ev;
     pathData.cost = mincost+GetWeight(sv,ev);
     PQ.PQInsert(pathData);
            }        }      }  }
        if (ev == eVertex)
      return mincost;
     else
      return -1;
}
  
template<class T>
T GetVertex(Graph<T> G,int pos)
{ int i, n=G.NumberOfVertices( );
   if(pos<0||pos>=n)
    {cerr<<"There are not so many vertices!";
      return 0; }
   VertexIterator<T> liter(G);
    i = 0;
   while(!liter.EndOfList( ) && i != pos)
     {     i++;
  liter.Next( );  }
    return liter.Data( );
}
template<class T>
void ShortestPathDijkstra(Graph<T> G, int v0,int *D,int**P)
{ int i, j,k,l,min, n=G.NumberOfVertices( );
  T u,v,w;
  u=GetVertex(G,v0);
  int *final=new int[n];
  for( i=0;i<n;i++)
   { final[i]=0;
     v=GetVertex(G,i);
     for(j=0;j<n;j++)P[i][j]=0;//initial P[i][j]
     D[i]=G.GetWeight(u,v);   //initial D[i]
     if(D[i]<MaxInt){ P[i][v0]=1;P[i][i]=1;}
         // p[i][j]=1 iff vertex j is in the path from v0 to i
    }
D[v0]=0;  final[v0]=1;
  for(i=1;i<n;i++)
   { min=MaxInt;
     for(j=1;j<n;j++) //Get the minimum D[k] 
     if(final[j]==0) //vertex j has not marked.
  if(D[j]<min)
    { k=j;  min=D[j];}
     final[k]=1;    //marked vertex k,
     v=GetVertex(G,k); //found the shortest path     
    for(j=1;j<n;j++)
      { w=GetVertex(G,j); l=G.GetWeight(v,w)+min;
 if(!final[j]&&(l<D[w]))
  {  D[w]=l;  //renew D[w]
     P[j]=P[k];  P[j][j]=1; }       }  }  }
void main( )
{ Graph<char> G;
  G.ReadGraph("sctest.dat");
  int n=G.NumberOfVertices( );
  int *D=new int[n];
  int **P=new (int**[n])[n];
  ShortestPathDijkstra(G,0,D,P);
  for(int i=0;i<n;i++)
   { cout<<"P["<<i<<"]={ ";
     cout<<P[i][0];
     for(int j=1;j<n;j++)
     cout<<","<<P[i][j];
     cout<<"}"<<endl;
   }
}

posted on 2011-12-31 09:18  rexminix  阅读(178)  评论(0)    收藏  举报