PATL2_026 小字辈
思路:
用結(jié)構(gòu)體Person{
int father; ?
int bf;
vector<int> son;
} p[100001];
/*
p[i].father表示表示第i個人的上一輩編號
p[i].bf表示第i個人的輩分
p[i].son 表示第i個人的兒子們
*/
用隊列從祖宗開始 下一代等于上一代的輩分加一 祖宗輩分為1
?
代碼如下:
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int n,maxBF=1,zz;
/*?
?? ?p[i].father表示表示第i個人的上一輩編號?
?? ?p[i].bf表示第i個人的輩分?
?? ?p[i].son 表示第i個人的兒子們?
*/?? ?
struct Person{
?? ?int father; ?
?? ?int bf;
?? ?vector<int> son;
}p[100001];?
?? ??? ??
void getBF();
int main()
{
?? ?int flag = 1;
?? ?cin>>n;
?? ?for(int i=1;i<=n;i++){
?? ??? ?cin>>p[i].father;
?? ??? ?if(p[i].father != -1)
?? ??? ??? ?p[p[i].father].son.push_back(i); //在i的上一輩的兒子數(shù)組中添加 i?
?? ??? ?else{?? ??? ??? ??? ??? ??? ??? ??? ? //i是祖宗?
?? ??? ??? ?zz = i;
?? ??? ??? ?p[i].bf = 1;
?? ??? ?}?
?? ?}?
?? ?getBF();
?? ?cout<<maxBF<<endl;
?? ?for(int i=1;i<=n;i++){
?? ??? ?if(p[i].bf == maxBF){
?? ??? ??? ?if(flag){
?? ??? ??? ??? ?cout<<i;
?? ??? ??? ??? ?flag = 0;
?? ??? ??? ?}
?? ??? ??? ?else
?? ??? ??? ??? ?cout<<" "<<i;
?? ??? ?}
?? ?}
?? ?cout<<endl;
?? ?return 0;?? ?
}
void getBF()
{
?? ?queue<int> q;
?? ?q.push(zz);
?? ?while(!q.empty()){
?? ??? ?int t = q.front();
?? ??? ?q.pop();
?? ??? ?for(int i=0;i<p[t].son.size();i++){
?? ??? ??? ?int son = p[t].son[i];
?? ??? ??? ?p[son].bf = p[t].bf + 1;
?? ??? ??? ?if(p[son].bf>maxBF)
?? ??? ??? ??? ?maxBF = p[son].bf;
?? ??? ??? ?q.push(son);
?? ??? ?}
?? ?}
}
總結(jié)
以上是生活随笔為你收集整理的PATL2_026 小字辈的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poco资料
- 下一篇: openstack 利用neutron-