最爱的城市
#include<vector>
#include<climits>
#include<iostream>
using namespace std;
int path = 0;
void dfs(vector<vector<int>>& city, vector<bool>& visited, int city2, int startindex, int* result)
{if (startindex == city2){if (path < *result)*result = path;return;}int i = startindex;for (int j = 0;j < city[startindex].size();j++){if (city[i][j] == 0 || visited[j] == true)//到不了或者已经去过的城市continue;path += city[i][j];visited[j] = true;dfs(city, visited, city2, j, result);path -= city[i][j];visited[j] = false;}
}
int main()
{int n = 0;//城市int m = 0;//线段//处理输入while (cin >> n >> m)//有多重输入{//用数组来存每个城市到其他城市的距离vector<vector<int>>city(n + 1, vector<int>(n + 1, 0));for (int i = 0;i < m;i++){int x = 0;int y = 0;cin >> x >> y;cin >> city[x][y];city[y][x] = city[x][y];}int city1 = 0;int city2 = 0;cin >> city1 >> city2;//记录已经走过的城市vector<bool>visited(n + 1, false);visited[city1] = true;int result = INT_MAX;dfs(city, visited, city2, city1, &result);//深度优先搜索,也可以说是回溯吧,这题写的一样if (result == INT_MAX)cout << "No path" << endl;elsecout << result << endl;}
}