庞发月


私信TA

用户名:PANGFAYUE

访问量:469

签 名:

等  级
排  名 14029
经  验 851
参赛次数 2
文章发表 2
年  龄 0
在职情况 学生
学  校 湖南大学
专  业

  自我简介:

#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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区