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


    题意:

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

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

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

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

    代码:

     1 #include <iostream>
     2 #include <queue>
     3 #include <cstdio>
     4 #include <algorithm>
     5 #include <cmath>
     6 #include <cstring>
     7 #define INF 0x3f3f3f3f
     8 
     9 using namespace std;
    10 typedef long long ll;
    11 const int maxn = 50010*2;
    12 int head[maxn],nxt[maxn],cost[maxn],u[maxn];
    13 int cnt = 0;
    14 ll sum = 0,ans = 0;
    15 void Add_edge(int _u,int _v,int _c){
    16     u[cnt] = _u; cost[cnt] = _c; nxt[cnt] = head[_v]; head[_v] = cnt++;
    17 }
    18 
    19 ll read(){//这种输入处理要比scanf/printf要快一些
    20     ll x = 0,f = 1;
    21     char ch = getchar();
    22     if(!isdigit(ch)){
    23         if(ch == '-'){
    24             f = -1;
    25             ch = getchar();
    26         }
    27     }
    28     while(isdigit(ch)){
    29         x = x*10 + ch - '0';
    30         ch = getchar();
    31     }
    32     return x*f;
    33 }
    34 
    35 void dfs(int now, ll res, int fa){
    36     ans = max(ans, res);
    37     for(int i = head[now]; ~i; i = nxt[i]){
    38         if(u[i]!=fa){
    39             dfs(u[i], res+(ll)cost[i], now);
    40         }
    41     }
    42     return;
    43 }
    44 
    45 int main(){
    46     memset(head,-1,sizeof head);
    47     int n = read(),x = read();
    48 //    int n,x;
    49 //    scanf("%d%d",&n,&x);
    50     for(int i = 0; i<n-1; i++){
    51         int u,v,w;
    52         u = read();v = read();w = read();
    53         //scanf("%d%d%d",&u,&v,&w);
    54         Add_edge(u,v,w);
    55         Add_edge(v,u,w);
    56         sum += w;
    57     }
    58 
    59     dfs(x, 0, 0);
    60     printf("%lld
    ",sum*2-ans);
    61     return 0;
    62 }
    View Code
  • 相关阅读:
    bzoj 3308 九月的咖啡店
    8.13模拟赛
    8.10模拟赛
    8.9模拟赛
    8.8模拟赛
    Codeforces Round #406 (Div. 2) D. Legacy (线段树建图dij)
    BZOJ 2957: 楼房重建 (分块)
    SPOJ BGSHOOT
    Codeforces Round #404 (Div. 2) E. Anton and Permutation(树状数组套主席树 求出指定数的排名)
    Lightoj-1356 Prime Independence(质因子分解)(Hopcroft-Karp优化的最大匹配)
  • 原文地址:https://www.cnblogs.com/sykline/p/9737869.html
Copyright © 2020-2023  润新知