#include<map> #include<math.h> #include<vector> #include<iostream> #include<algorithm> using namespace std; struct tree; int maxnum=0;//最大的节点数 tree* maxnode; map<int,tree*>mp; //用结构体创建一棵树 struct tree{ int num,name;//num:表示这个节点下有多少个子节点,name:这个节点存储的字母 tree *fa;//一个结构体指针,存放父亲的地址 vector<tree*>son;//vector相当于数组,用来存储所有儿子的结构体数组 tree(int n){//这个是构造函数,45行new语句会调用 num=0; name=n; fa=NULL; } void addson(tree* so){//增加儿子,调用这个函数后,儿子数加一(23行) num++; if(maxnum<num){//找出最多的节点 maxnum=num; maxnode=this;//this是个指针,对应的地址是儿子最多的节点 } son.push_back(so);//这是vector的成员函数,相当于往son数组里边加了一个指针 so->fa=this;//新儿子的父亲地址 } }; bool cmp(tree *a,tree *b){ return a->name<b->name; } int main(){ int n,m,x,y; tree *node,*temp; cin>>n>>m; for(int i=0;i<m;i++){ cin>>x>>y; node=new tree(y);//重新申请一个tree的空间,用来放新的节点 ,同时调用17行的函数 if(mp.find(x)!=mp.end())temp=mp[x]; else temp=new tree(x); temp->addson(node); mp[x]=temp; mp[y]=node; } temp=maxnode; sort(temp->son.begin(),temp->son.end(),cmp);//调用排序函数,在algorithm库里 while(temp->fa!=NULL)temp=temp->fa; cout<<temp->name<<endl<<maxnode->name<<endl; for(int i=0;i<maxnum;i++){ temp=maxnode->son[i]; cout<<temp->name<<" "; } return 0; }
0.0分
0 人评分
大神老白 (C语言代码)浏览:686 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:585 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:535 |
班级人数 (C语言代码)浏览:972 |
C语言程序设计教程(第三版)课后习题6.5 (C语言代码)浏览:503 |
C二级辅导-计负均正 (C语言代码)浏览:659 |
非常简单的算法,题解1049:C语言程序设计教程(第三版)课后习题11.1 (C语言代码)浏览:635 |
P1002 (C语言代码)浏览:1018 |
1074题 初学者,求帮忙看下,不知道哪错了浏览:295 |
纪念品分组 (C++代码)浏览:870 |