1004 Counting Leaves (30分) (树的储存)

题目链接

代码 DFS

#if 0
#include<vector>
using namespace std;
#include <iostream>
vector<int>nodes[100];        
int depth[100];
int maxdepth = 0;
void dfs(int index,int deep) {
	if (nodes[index].size() == 0) {// judge whether ID[index] has sons
		depth[deep]++;
		maxdepth = deep > maxdepth ? deep : maxdepth;//for later output at line 33
		return;
	}
	else {
		for(int i=0;i<nodes[index].size();i++)
		dfs(nodes[index][i] , deep + 1);
	}
}
int main() {
	int N, M;
	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		int id, num;
		cin >> id>>num;
		for (int j= 0; j < num; j++) {
			int son;
			cin >> son;
			nodes[id].push_back(son);//add son one by one
		}
	}
	if (N == 0)return 0;
	dfs(1, 0);
	cout << depth[0];
	for (int i = 1; i <= maxdepth; i++) {
		cout << " " << depth[i];
	}
	return 0;
}
#endif

代码 BFS

#if 0
#include<vector>
using namespace std;
#include <iostream>
#include<queue>
vector<int>nodes[100];
int depth[100],maxdepth = 0;
void bfs(int index1) {
	int deep = 0;
	queue<int>temp1, temp2;//"temp" includes all nodes in same depth
	temp1.push(index1);
	while(!temp1.empty()) {
		int index2 = temp1.front();
		temp1.pop();
		if (nodes[index2].size() == 0) { //no son
			depth[deep]++; 
			maxdepth = deep > maxdepth ? deep : maxdepth;
		} 
		for (int i = 0; i < nodes[index2].size(); i++) {     //push each son into temp2
			temp2.push(nodes[index2][i]);
		}
		if (temp1.empty()) {
			temp1.swap(temp2);
			deep++;
		}		
	}
}
int main() {
	int N, M;
	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		int id, num;
		cin >> id >> num;
		for (int j = 0; j < num; j++) {
			int son;
			cin >> son;
			nodes[id].push_back(son);//add son one by one
		}
	}
	if (N == 0)return 0;
	bfs(1);
	cout << depth[0];
	for (int i = 1; i <= maxdepth; i++) {
		cout << " " << depth[i];
	}
	return 0;
}
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值