pta ds 7-2 小字辈 (25分) 广度优先优先搜索
继续补题,
7-2 小字辈 (25分)
本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。
输入格式:
输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。
输出格式:
首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。
输入样例:
9
2 6 5 5 -1 5 6 4 7
输出样例:
4
1 9
作者
陈越
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
普普通通查找每个节点的父节点来找到它的辈分,最后再一遍输出会超时
#include<stdio.h> #include<iostream> #include<queue> using namespace std; queue<int> q; int main(){ int n; scanf("%d",&n); int a[n+1][2]={}; for(int i=1;i<=n;i++){ scanf("%d",&a[i][0]); } int max = 1; for(int i=1;i<=n;i++){ int temp = a[i][0]; int cnt = 1; while(temp!=-1){ temp = a[temp][0]; cnt++; } a[i][1] =cnt; if(cnt>max)max = cnt; } cout<<max<<endl; for(int i=1;i<=n;i++){ if(a[i][1] == max)q.push(i); } while(1){ cout<<q.front(); q.pop(); if(q.empty()){ break; } else{ printf(" "); } } return 0; }
利用广度优先搜索会快上不少(依然使用multimap来构建树理由是代码量小
#include<stdio.h> #include<iostream> #include<map> #include<queue> using namespace std; multimap<int,int> tree; queue<int> q; queue<int> ans; void level(int root){ int last = root; int tail; int level = 0; multimap<int,int>::iterator iter; q.push(root); while(!q.empty()){ root = q.front(); // cout<<root<<" "; ans.push(root); q.pop(); for(iter = tree.lower_bound(root);iter != tree.upper_bound(root) ;iter++){ q.push(iter->second); tail = iter->second; } if(last == root){ level++; last = tail; // cout<<endl; if(!q.empty()) while(!ans.empty()) ans.pop(); } } cout<<level<<endl; while(1){ cout<<ans.front(); ans.pop(); if(ans.empty()){ break; } else cout<<" "; } } int main(){ int n; cin>>n; int temp; int root; for(int i=1;i<=n;i++){ cin>>temp; tree.insert(make_pair(temp,i)); if(temp == -1)root = i; } level(root); return 0; }