以第一个关键字作为约束,用Floyd算法求解出多条最优的路径,再以第二个关键字作为约束,进一步筛选出最优的路径。
比如:第一关键字为距离,第二关键字为花费。
最后遍历这些路径使用递归函数
关键代码片段
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Graph[i][k] <= 0 || Graph[k][j] <= 0 || i == j) //以-1表征不相连接的边
continue;
if ((Graph[i][j] > 0 && Graph[i][j] > Graph[i][k] + Graph[k][j]) || (Graph[i][j] < 0))
{
Graph[i][j] = Graph[i][k] + Graph[k][j];
Path[i][j].clear();//***
Path[i][j].insert(Path[i][j].end(), Path[i][k].begin(), Path[i][k].end());//***
}
else if (Graph[i][j] == Graph[i][k] + Graph[k][j])
{
Path[i][j].insert(Path[i][j].end(), Path[i][k].begin(), Path[i][k].end());//***
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------------------
对于Dijkstra算法,同理,求多关键字约束下的最优路径见题目:http://ac.jobdu.com/problem.php?pid=1008思路:在distance数组中挑选最小值以及更新辅助数组时,同时以這些关键字作为参考筛选。关键代码片段//其中Graph存储距离信息,为第一关键字,Pay为每条路径的花费信息,为第二关键字void Dijkstra(int **const Graph, int **Pay, int n, int source, int *distance, int *cost)
{
bool *decided = new bool[n];
//初始化三个矩阵decided、distance、cost
for (int i = 0; i < n; i++)
{
if (i == source)
decided[i] = true;
else
decided[i] = false;
distance[i] = Graph[source][i];
cost[i] = Pay[source][i];
}
//n-1轮刷新距离矩阵
for (int count = 1; count < n; count++) //需要n-1轮进行刷新
{
//找到最小权值的边,第一关键字为dist,第二关键字为cost
int minDist = MAX, minIndex = -1;
for (int i = 0; i < n; i++)
{
if (!decided[i] && distance[i] < minDist)
{
minDist = distance[i];
minIndex = i;
}
else if (!decided[i] && distance[i] == minDist)
{
if (cost[i] < cost[minIndex])
minIndex = i;
}
}
decided[minIndex] = true;
//一轮刷新
for (int i = 0; i < n; i++)
{
if (!decided[i])
{
if (distance[i] > minDist + Graph[minIndex][i])
{
distance[i] = minDist + Graph[minIndex][i];
cost[i] = cost[minIndex] + Pay[minIndex][i];
}
else if (distance[i] == minDist + Graph[minIndex][i])
{
if (cost[i] > cost[minIndex] + Pay[minIndex][i])
{
cost[i] = cost[minIndex] + Pay[minIndex][i];
}
}
}
}
}
delete decided;
}