PAT-ADVANCED1094——The Largest Generation

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/83625116

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED

原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805372601090048

题目描述:

题目翻译:

1094 人数最多的一代

族层次结构通常由谱系树呈现,其中同一级别上的所有节点属于同一代。你的任务是找到人口最多的一代。

输入格式:

每个输入文件包含一个测试用例。在每个测试用例中,第一行给出了两个数字:0 < N < 100,代表树中的节点个数;M( < N)代表非叶子节点个数。接下来的M行,每行都是下述格式:

ID K ID[1] ID[2] ... ID[K]

ID是一个2位数字,表示一个非叶子节点,K是该节点的孩子数量,紧跟着的是一串ID值以及该ID值对应的孩子数量。为了简便,我们假设根节点的ID值是01。一行中的所有数字被一个空格分开。

输出格式:

对每个测试用例,打印出人数最多的一代的人数及其代数。假设这样的代数是唯一的,根结点是第一代。

输入样例:

23 13
21 1 23
01 4 03 02 04 05
03 3 06 07 08
06 2 12 13
13 1 21
08 2 15 16
02 2 09 10
11 2 19 20
17 1 22
05 1 11
07 1 14
09 1 17
10 1 18

输出样例:

9 4

知识点:树的广度优先遍历、深度优先遍历

思路一:深度优先遍历的同时记录节点的层级

本题和PAT-ADVANCED1079——Total Sales of Supply ChainPAT-ADVANCED1090——Highest Price in Supply Chain考察的知识点相同,解法也近乎相同。

时间复杂度和空间复杂度均是O(N)。

C++代码:

#include<iostream>
#include<vector>

using namespace std;

struct node {
	vector<int> child;
};

int N;
int M;
node Node[101];
int count[101] = {0};	//第i层有count[i]个成员

void dfs(int nowVisit, int level); 

int main(){
	cin >> N >> M;
	int ID, K, num;
	for(int i = 0; i < M; i++){
		cin >> ID >> K;
		for(int j = 0; j < K; j++){
			cin >> num;
			Node[ID].child.push_back(num); 
		}
	}
	dfs(1, 1);
	int maxGeneration = 0;
	for(int i = 1; i <= N; i++){
		if(count[i] > count[maxGeneration]){
			maxGeneration = i;
		}
	}
	cout << count[maxGeneration] << " " << maxGeneration << endl;
	return 0;
}

void dfs(int nowVisit, int level){
	count[level]++;
	if(Node[nowVisit].child.size() == 0){
		return;
	}
	for(int i = 0; i < Node[nowVisit].child.size(); i++){
		dfs(Node[nowVisit].child[i], level + 1);
	}
}

C++解题报告:

思路二:广度优先遍历的同时为每个节点添加层级信息

时间复杂度和空间复杂度均是O(N)。

C++代码:

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct node {
	int level;
	vector<int> child;
};

int N;
int M;
node Node[101];
int count[101] = {0};	//第i层有count[i]个成员

void bfs(int nowVisit);

int main() {
	cin >> N >> M;
	int ID, K, num;
	for(int i = 0; i < M; i++) {
		cin >> ID >> K;
		for(int j = 0; j < K; j++) {
			cin >> num;
			Node[ID].child.push_back(num);
		}
	}
	bfs(1);
	for(int i = 1; i <= N; i++) {
		count[Node[i].level]++;
	}
	int maxGeneration = 0;
	for(int i = 1; i <= N; i++) {
		if(count[i] > count[maxGeneration]) {
			maxGeneration = i;
		}
	}
	cout << count[maxGeneration] << " " << maxGeneration << endl;
	return 0;
}


void bfs(int nowVisit) {
	queue<int> q;
	Node[nowVisit].level = 1;
	q.push(nowVisit);
	while(!q.empty()) {
		int now = q.front();
		q.pop();
		for(int i = 0; i < Node[now].child.size(); i++) {
			Node[Node[now].child[i]].level = Node[now].level + 1;
			q.push(Node[now].child[i]);
		}
	}
}

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/83625116