pta数据结构day9

总结:写了三题,花费半天,准备先把leetbook的二叉树先写一遍,因为pta没有最优解,写起来逻辑并不顺畅。

先看树种统计,比较另外2题简单;

题目详情 - 案例4-1.6 树种统计 (pintia.cn)

#include<iostream>
#include<map>
#include<string>
using namespace std;

int main() {
	map<string, int>mp;
	int n;
	cin >> n;
	cin.get();//blank
	string s;
	for (int i = 0; i < n; i++) {
		getline(cin, s);
		map<string, int>::iterator it = mp.find(s);//原来有这个元素,统计个数+1;
		if (it != mp.end()) {
			it->second += 1;
		}
		else {//没有这个元素,创建并初始个数为1
			mp.insert(make_pair(s, 1));
		}
	}
	cout.setf(ios_base::fixed);
	cout.precision(4);
	for (map<string, int>::iterator i = mp.begin(); i != mp.end(); i++) {
		cout << i->first << ' ' << (i->second)*100.0/n<<'%' << endl;
	}
	return 0;
}

第二题是树的同构,考察递归的逻辑,可以参考mooc视频多写几次;

题目详情 - 基础实验4-2.1 树的同构 (pintia.cn) 

#include<iostream>
using namespace std;
#define NULL -1
struct node {
	char data;
	int left, right;
}p[10],q[10];
int input(node p[],int n) {
	int check[10]={0},root=NULL;
	char ch;
	for (int i = 0; i < n; i++) {
		cin.get();//blank
		cin >> p[i].data;
		cin >> ch;
		if (ch == '-') {
			p[i].left = -1;
		}
		else {
			p[i].left = ch - '0';
			check[p[i].left] = 1;
		}
		cin >> ch;
		if (ch == '-') {
			p[i].right = -1;
		}
		else {
			p[i].right = ch - '0';
			check[p[i].right] = 1;
		}
	}
	for (int i = 0; i < n; i++) {
		if (check[i] == 0) {
			root = i;
		}
	}
	return root;
}
bool is_tonggou(int r1,int r2) {
	if (r1 == NULL && r2 == NULL) {
		return 1;
	}
	else if ((r1 == NULL && r2 != NULL) || (r1 != NULL && r2 == NULL)) {
		return 0;
	}
	else if (p[r1].data != q[r2].data) {
		return 0;
	}
	else if ((p[r1].left == NULL) && (q[r2].left == NULL)) {
		return is_tonggou(p[r1].right, q[r2].right);
	}
	else if ((p[r1].left != NULL) && (q[r2].left != NULL)&&(p[p[r1].left].data==q[q[r2].left].data)) {
		return is_tonggou(p[r1].left, q[r2].left) && is_tonggou(p[r1].right, q[r2].right);
	}
	else {
		return is_tonggou(p[r1].left, q[r2].right) && is_tonggou(p[r1].right, q[r2].left);
	}
}
int main() {
	int n,m,root1,root2;
	cin >> n;
	root1=input(p,n);
	cin >> m;
	if (n != m) {
		cout << "No\n";
		return 0;
	}
	root2=input(q,m);
	bool flag = is_tonggou(root1,root2);
	if (flag) {
		cout << "Yes\n";
	}
	else {
		cout << "No\n";
	}
	return 0;
}

最后是目录树,比较复杂,需要再写一次;

题目详情 - 基础实验4-2.6 目录树 (pintia.cn) 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值