北邮机试 | bupt oj | 92. 统计节点个数

本文介绍了一种算法,用于统计有向树中被称为p节点的特定类型节点的数量。p节点定义为其度(即入度加出度)不小于其所有子节点及父节点的度。文章提供了完整的C++代码实现,包括节点结构定义、插入边的方法以及统计p节点数量的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

统计节点个数

时间限制 1000 ms 内存限制 65536 KB

题目描述

给出一棵有向树,一共有N(1<N≤1000)个节点,如果一个节点的度(入度+出度)不小于它所有儿子以及它父亲的度(如果存在父亲或儿子),那么我们称这个节点为p节点,现在你的任务是统计p节点的个数。

如样例,第一组的p节点为1,2,3;第二组的p节点为0。

输入格式

第一行为数据组数T(1≤T≤100)。
每组数据第一行为N表示树的节点数。后面为N−1行,每行两个数x,y(0≤x,y<N),代表y是x的儿子节点。

输出格式

每组数据输出一行,为一个整数,代表这棵树上p节点的个数。

输入样例

2
5
0 1
1 2
2 3
3 4
3
0 2
0 1

输出样例

3
1

AC代码

#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
    int father;
    int degree;
    vector<int> son;
    Node(int father=-1,int degree=0):father(father),degree(degree){}
}Node,*PNode;
void insertLine(Node forest[],int a,int b){
    forest[a].degree++;
    forest[b].degree++;
    forest[a].son.push_back(b);
    forest[b].father=a;
}
int countP(Node forest[],int n){
    int ans=0;
    for(int i=0;i<n;i++){
        Node p=forest[i];
        int pDegree = p.degree;
        bool flag = true;
        if(p.father!=-1){
            if(pDegree<forest[p.father].degree){
                flag = false;
                continue;
            }
        }
        vector<int> &pson = p.son;
        for(unsigned int j=0;j<p.son.size();j++){
            if(pDegree<forest[pson[j]].degree){
                flag = false;
                break;
            }
        }
        if(flag){
            ans++;
        }
    }
    return ans;
}
int main()
{
    int t,n,a,b;
    cin>>t;
    while(t--){
        cin>>n;
        Node forest[n];
        for(int i=0;i<n-1;i++){
            cin>>a>>b;
            insertLine(forest,a,b);
        }
        int ans = countP(forest,n);
        cout<<ans<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值