求图中最长路径

求最长路径函数:

vectorPath;
vectorLongPath;
bool first=true;
float pathSum,longPathSum;
int paths=0;
vector> status(6,vector(6,0));   //顶点状态

void getRoad(vector> prox,int start,int end)
{
	Path.push_back(start);		
	status[start][end]=1;
	if(prox[start][end]>0)
	{
	   pathSum+=prox[start][end];
	   Path.push_back(end);
		vector::iterator iter;
		if(first)
		{
			for(iter=Path.begin();iter!=Path.end();++iter)
			{
				LongPath.push_back(*iter);
			}
			first=false;
			longPathSum=pathSum;
		}
		else
		{
			if(pathSum>longPathSum)
			{
				LongPath.clear();
				for(iter=Path.begin();iter!=Path.end();++iter)
			   {
				  LongPath.push_back(*iter);
		       }
				 longPathSum=pathSum;
			}
		}
		Path.pop_back();
		pathSum-=prox[start][end];
	}

	 
	 for(int i=0;i0))
	   {
			pathSum+=prox[start][i];
			getRoad(prox,i,end);
			pathSum-=prox[start][i];
	    }
	 }
	   Path.pop_back();
       status[start][end]=0;
}

调用方法:

vector> mz(6,vector(6,0.0)); //图中的权值
//测试最长路径
	mz[0][1]=0.3;
	mz[1][2]=1.0;
	mz[2][3]=0.3;
	mz[3][0]=0.3;
	mz[1][4]=0.6;
	mz[4][2]=0.7;
	mz[2][5]=0.4;
	mz[5][3]=0.3;
	getRoad(mz,4,1);    


你可能感兴趣的:(C++)