我不理解这个dfs实现的语法
i am not understanding the syntax of this dfs implementation
这是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的实现,它出现在一个比赛的社论中。完整的代码如下。如果有人能帮助我理解的这段代码,那就太好了
#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;
}
这是标准的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++语言细节感兴趣,你可以试试这个参考。
此外,还有更可读的方法来做同样的事情。但在竞争性编码的情况下,由于编码部分的时间限制而不被接受。这就是为什么它不是一个学习任何良好做法的好地方。
您还可以用类似的东西替换for-loop
中的代码
for(int neighborNodeIndx = 0 ; neighborNodeIndx < (int)v[u].size(); neighborNodeIndx ++)
{
neighborNode = v[u][neighborNodeIndx];// this is similar to i
...
}
相关文章:
- 解释通过 lex/flex 实现 C/C++嵌套的"#include "Header""语法?
- priority_queue使用降序向量实现最小堆的语法差异
- 如何在编译器C++不智能的情况下实现 GLSL vec* 构造语法?
- 如何使用 Boost.Asio 正确实现异步/等待语法
- 像这样的PIMPL实现是否有任何简单的语法
- 在任何编译语言中实现以下语法(用于工厂设计模式)? 最好是 Kotlin,C++
- 如何使用自然外观的语法实现线程安全容器
- 在C 中,可以用语法[i,j,..]实现访问数组元素的功能,而语法就像numpy中的ndarray样式一样
- 我不理解这个dfs实现的语法
- 如何使用两个单独的语法实现计算机翻译器
- 强类型枚举的语法实现错误
- GCC 4.4 不实现 C++11 范围循环.它还支持哪些其他范围循环语法
- 模板的赋值运算符(成员函数)实现的正确语法
- 实现功能齐全的移位流语法
- 用C++实现Matlab语法
- 在不使用专用语法的情况下,为不同类型的不同方式实现模板类的方法是否有效C++?
- Boost是如何实现这样的语法的
- 在我的解释器上为脚本代码实现语法检查器的最佳方式是什么
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 通过move赋值实现B=f(A)语法