版权声明:欢迎转载 https://blog.csdn.net/stone_fall/article/details/88421503
时间限制 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;
}