水图(牛客练习赛(DFS搜索))

本文介绍了一个图论游戏问题,目标是从指定起点出发,遍历所有节点的最短路径计算。通过深度优先搜索(DFS)算法,实现对无向连通图的遍历,并给出了一种有效求解策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

小w不会离散数学,所以她van的图论游戏是送分的

小w有一张n个点n-1条边的无向联通图,每个点编号为1~n,每条边都有一个长度
小w现在在点x上
她想知道从点x出发经过每个点至少一次,最少需要走多少路

思路:从当前位置开始dfs深搜,注意已经搜过的上一个点就不要搜了不然就成死循环了。

确实是个水题,但因为图论搜索这方面练习的太少了,看到题却没有往搜索上考虑,太low了!!!

代码:

#include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#define INF 0x3f3f3f3f

using namespace std;
typedef long long ll;
const int maxn = 50010*2;
int head[maxn],nxt[maxn],cost[maxn],u[maxn];
int cnt = 0;
ll sum = 0,ans = 0;
void Add_edge(int _u,int _v,int _c){
    u[cnt] = _u; cost[cnt] = _c; nxt[cnt] = head[_v]; head[_v] = cnt++;
}

ll read(){//这种输入处理要比scanf/printf要快一些
    ll x = 0,f = 1;
    char ch = getchar();
    if(!isdigit(ch)){
        if(ch == '-'){
            f = -1;
            ch = getchar();
        }
    }
    while(isdigit(ch)){
        x = x*10 + ch - '0';
        ch = getchar();
    }
    return x*f;
}

void dfs(int now, ll res, int fa){
    ans = max(ans, res);
    for(int i = head[now]; ~i; i = nxt[i]){
        if(u[i]!=fa){
            dfs(u[i], res+(ll)cost[i], now);
        }
    }
    return;
}

int main(){
    memset(head,-1,sizeof head);
    int n = read(),x = read();
//    int n,x;
//    scanf("%d%d",&n,&x);
    for(int i = 0; i<n-1; i++){
        int u,v,w;
        u = read();v = read();w = read();
        //scanf("%d%d%d",&u,&v,&w);
        Add_edge(u,v,w);
        Add_edge(v,u,w);
        sum += w;
    }

    dfs(x, 0, 0);
    printf("%lld\n",sum*2-ans);
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值