Input
Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
Output
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.
Sample Input2 1 01 1 02Sample Output
0 1
原题链接:
思路:
map匹配节点在数组中的下标,类似于索引功能
先读入数据,添加父子关系
然后DFS,确定层数并统计各层目标点个数
最后输出
CODE:
#include<iostream>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#define N 101
using namespace std;
typedef struct no
{string id;string son[N];int ns;
};
map<string,int> pos;
int m,n;
no p[N];
int mf=0;
int outp[N];
void dfs(string r,int fl)
{mf=max(mf,fl);if (p[pos[r]].ns==0){outp[fl]++;return ;}for (int i=0;i<p[pos[r]].ns;i++){dfs(p[pos[r]].son[i],fl+1);}return;
}int main()
{cin>>n>>m;int num=1;for (int i=0;i<m;i++){string a;cin>>a;int t;if (pos[a]==0){p[num].id=a;p[num].ns=0;pos[a]=num;t=num;num++;}else{t=pos[a];}int k;cin>>k;for (int j=0;j<k;j++){string ss;cin>>ss;p[t].son[p[t].ns]=ss;p[t].ns++;if (pos[ss]==0){p[num].id=ss;p[num].ns=0;pos[ss]=num;num++;}}}memset(outp,0,sizeof(outp));dfs("01",0);for (int i=0;i<mf;i++) cout<<outp[i]<<" ";cout<<outp[mf];return 0;
}
本文发布于:2024-01-31 17:35:21,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170669372030226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |