我不理解这个dfs实现的语法

i am not understanding the syntax of this dfs implementation

本文关键字:实现 语法 dfs 不理解      更新时间:2023-10-16

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