首页 > 其他 > 详细

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

时间:2018-10-02 21:24:26      阅读:187      评论:0      收藏:0      [点我收藏+]

题意:

小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\n",sum*2-ans);
61     return 0;
62 }
View Code

 

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

原文:https://www.cnblogs.com/sykline/p/9737869.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!