节点的度
题目描述
"节点的度"指以该节点为端点的边的条数。"偶点"指度为偶数的节点。
给你一棵n个节点的有根树,节点标号为1~n,1号节点为根节点。特别的,每个点的子节点个数不超过5。
请你输出该树中偶点的个数。
输入
第一行一个整数n。
以后n行,每行若干个整数。第i行,第一个数为mi,表示节点i的子节点个数。紧接着mi个整数,表示节点i子节点的编号。保证父节点编号小于子节点。
输出
一行一个整数,表示偶点个数。
输入
3
2 2 3
0
0
输出
1
可不可已改一下
#include<bits/stdc++.h>
using namespace std;
struct c{
int data;
c* next;
};
struct p{
int data;
c* child;
};
struct tree{
p a[100];
int n;
};
tree t;
int main()
{
cin>>t.n;
for(int i=1;i<=t.n;i++)
{
cin>>t.a[i].data;
t.a[i].child=NULL;
int cn;
cin>>cn;
if(cn!=0)
{
t.a[i].child=new c;
cin>>t.a[i].child->data;
t.a[i].child->next=NULL;
c*p=t.a[i].child;
while(cn){
c*s=new c;
cin>>s->data;
s->next=NULL;
p->next=s;
p=p->next;
cn--;
}
}
}
cout<<"1"<<endl;
for(int i=1;i<=t.n;i++){
c*k=t.a[i].child;
while(k)
{
cout<<t.a[i].data<<"."<<t.a[k->data].data<<endl;
k=k->next;
}
}
return 0;
}
def count_even_nodes(n, nodes):
# 创建一个长度为n+1的数组,用来存储节点的度数
degrees = [0] * (n+1)
# 遍历每个节点的子节点
for node, children in nodes.items():
# 计算节点的度数
degrees[node] = len(children)
# 遍历子节点并更新它们的度数
for child in children:
degrees[child] += 1
# 统计度数为偶数的节点个数
count = sum(1 for degree in degrees if degree % 2 == 0)
return count
使用示例:
nodes = {1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [], 6: []}
result = count_even_nodes(6, nodes)
print(result)
输出结果:
4
注: 在此解决方案中,我使用了一个长度为n+1的数组来存储每个节点的度数。然后遍历每个节点的子节点,更新它们的度数。最后,统计度数为偶数的节点个数,并返回结果。