2017-10-18 23 views
-2

这样的DFS功能可按代码片段: -我不理解的语法这DFS实现

void dfs(int u, int p) 
      { 
       if(p!=-1)d[u] = d[p]+1; 
       for(int i: v[u]) 
       { 
        if(i==p)continue; 
        dfs(i, u); 
       } 
      } 

我不理解这其中的DFS排在比赛的社论执行。完整的代码是follows.it将是非常好的,如果有人可以帮助我理解这一段代码

#include <bits/stdc++.h> 
     using namespace std; 
     #define int long long int 

     vector<int> d; 
     vector< vector<int> > v; 

     void dfs(int u, int p) 
     { 
      if(p!=-1)d[u] = d[p]+1; 
      for(int i: v[u]) 
      { 
       if(i==p)continue; 
       dfs(i, u); 
      } 
     } 

#undef int 
int main() 
{ 
#define int long long int 
ios_base::sync_with_stdio(0); 
cin.tie(0); 
cout.tie(0); 

int n; 
cin>>n; 
v.resize(n); 
d.resize(n); 
for(int i = 0;i<n-1;i++) 
{ 
    int x, y; 
    cin>>x>>y; 
    v[x-1].push_back(y-1); 
    v[y-1].push_back(x-1); 
} 
d[0] = 0; 
dfs(0, -1); 
int q; 
cin>>q; 
while(q--) 
{ 
    int x, y; 
    cin>>x>>y; 
    if((d[x-1]+d[y-1])&1)cout<<"Odd"<<endl; 
    else cout<<"Even"<<endl; 
} 


return 0; 

}

+5

代码中写的不好,没有人真正应该使用快速黑客替换for-loop代码学习材料。案例:用宏重新定义一种基本的内置类型; [包括''](http://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h);命名错误的变量;没有文件或评论。如果你想学习编程C++,那么[阅读好书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)或去学校。 –

+0

没有什么像重新定义关键字那样激发你的代码。接下来'#define double float' –

+0

@Someprogrammerdude几天前,我正在审查一些考试试卷,以便在我们的办公室进行新一期招聘。我感到惊讶的是,每个人都包含'bits/stdC++。h'。我问了其他人,现在主要关注的是哪些书,我的一位年轻同事回答说'Code :: Blocks'自动生成这个。 – taskinoor

回答

0

这是标准的DFS代码。

根的父母是-1。所以在其他情况下,我们会有一位家长。

对于所有那些节点,我们将访问它的邻居。

  for(int i: v[u]) // every neighbor of u except the parent. 
      { 
       if(i==p)continue; // avoiding the parent from which it is traversed 
       dfs(i, u); // recursively search there. 
      } 

如果你有兴趣正在使​​用你可以试试这个reference C++语言的细节。

也有更多可读的方式来做同样的事情。但是在竞争性编码的情况下,由于编码部分的时间限制而不被接受。这就是为什么它是了解任何良好做法的不好的地方。

你还可以用像提交“constest”网站或“网上评委”往往这

for(int neighborNodeIndx = 0 ; neighborNodeIndx < (int)v[u].size(); neighborNodeIndx ++) 
    { 
     neighborNode = v[u][neighborNodeIndx];// this is similar to i 
     ... 
    } 
+0

谢谢@coderredoc –