传递悄悄话
层序遍历数组形式的下标如下
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1010, M = N * 2;
int n;
int h[N], e[M], ne[M], idx;
int v[N], dist[N];
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u)
{
st[u] = true;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
dist[j] = dist[u] + v[j];
dfs(j);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
memset(h, -1, sizeof h);
int x;
while (cin >> x) v[++n] = x;
for (int i = 1; i <= n / 2; i++)//二叉树的最后一个分支(非叶)节点为n/2
{
if (v[i] == -1) continue;
int a = i * 2, b = i * 2 + 1;
//若下标在范围内且左右儿子存在
if (a <= n && v[a] != -1) add(i, a), add(a, i);//无向边
if (b <= n && v[b] != -1) add(i, b), add(b, i);
}
dfs(1);//1号点为根节点
int res = 0;//dist数组存的是根节点1到其他所有点的距离
for (int i = 1; i <= n; i++) res = max(res, dist[i]);
cout << res << '\n';
return 0;
}
标签:遍历,dist,idx,int,层序,ne,二叉树
From: https://www.cnblogs.com/Tshaxz/p/18688564