增加了路径,记录从哪一个点过来的,其余同1003题一样
#include <iostream>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
using namespace std;
int n,m,c1,c2;
int **roadcost;
int **road;
int *resultpath;
int roadlen = INT_MAX;
int totalcost = 0;
void DFS(int start, int end, int cost, int len, bool *visited, int *prev)
{
if(len > roadlen)
return ;
if(start == end)
{
if(len < roadlen)
{
roadlen = len;
totalcost = cost;
for(int i = 0; i < n; i++)
resultpath[i] = prev[i];
}
else if(len == roadlen)
{
if(cost < totalcost)
{
totalcost = cost;
for(int i = 0; i < n; i++)
resultpath[i] = prev[i];
}
}
return;
}
for(int i = 0; i < n; i++)
{
if(road[start][i] != INT_MAX && !visited[i])
{
visited[i] = true;
int temp = prev[i];
prev[i] = start;
DFS(i,end,cost + roadcost[start][i], len + road[start][i], visited, prev);
prev[i] = temp;
visited[i] = false;
}
}
}
void output(int *resultpath, int index)
{
if(c1 != index)
output(resultpath, resultpath[index]);
cout << index << " ";
}
int main()
{
bool *visited;
int *prev;
cin >> n >> m >> c1 >> c2;
prev = new int[n];
visited = new bool[n];
resultpath = new int[n];
road = (int **)malloc(sizeof(int *)*n);
roadcost = (int **)malloc(sizeof(int *)*n);
for(int i = 0; i < n; i++)
{
visited[i] = false;
road[i] = new int[n];
roadcost[i] = new int[n];
for(int j = 0; j < n; j++)
road[i][j] = INT_MAX;
}
int x,y;
for(int i = 0; i < m; i++)
{
cin >> x >> y;
cin >> road[x][y] >> roadcost[x][y];
road[y][x] = road[x][y];
roadcost[y][x] = roadcost[x][y];
}
for(int i = 0; i < n; i++)
{
if(road[c1][i] == INT_MAX)
prev[i] = -1;
else
prev[i] = c1;
}
visited[c1] = true;
DFS(c1, c2, 0, 0, visited, prev);
output(resultpath, c2);
cout << roadlen << " " << totalcost;
return 0;
}