刷题之最爱的城市(卡码网,图论)

最爱的城市

在这里插入图片描述

#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;
        else
            cout << result << endl;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值