【问题标题】:i am not understanding the syntax of this dfs implementation我不理解这个 dfs 实现的语法
【发布时间】:2017-10-18 06:26:13
【问题描述】:

这是一个dfs功能码sn-p:-

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 实现。完整代码如下。如果有人能帮我理解这段代码,那就太好了

#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;

}

【问题讨论】:

  • 提交给“竞赛”网站或“在线评委”的代码往往写得不好,而且没有人真正应该将其用作学习材料。恰当的例子:用宏重新定义基本的内置类型; Including &lt;bits/stdc++.h&gt;;命名错误的变量;没有文档或 cmets。如果你想学习 C++ 编程,那么read good books 或去学校。
  • 没有什么比重新定义关键字更能丰富您的代码了。接下来#define double float
  • @Someprogrammerdude 几天前,我正在审查我们办公室下一阶段应届生招聘的一些试卷。我很惊讶实际上每个人都包括bits/stdc++.h。我问其他人这些天学生主要看什么书,我的一位年轻同事回答说Code::Blocks 自动生成。
  • @taskinoor 我刚刚尝试过使用 Code::Blocks,除非你的同事使用 very 旧版本(比上一个将近两年前的二进制版本旧得多)它不会生成该包含。
  • @taskinoor 我也使用代码块,但它不这样做

标签: c++ algorithm graph


【解决方案1】:

这是标准的 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.
            }

如果您对正在使用的 c++ 语言详细信息感兴趣,可以试试这个reference

还有更易读的方式来做同样的事情。但是在竞争性编码的情况下,由于编码部分的时间限制而无法接受。这就是为什么它不是一个学习任何好的做法的地方。

您还可以将for-loop 中的代码替换为类似这样的代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多