pat 1079

1.Pat-1079

2.源代码

#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define maxSize 100010

typedef struct {
	int weight;//仓库中的数据 
	vector<int> child;//使用vector存储孩子节点---->节省空间 
}BiTree;


BiTree bt[maxSize];//申请一个这么大的BiTree类型数组 
double sum = 0.0;//存储总得金钱数 
double p,r;//number是结点个数,p是价格,r是增长率

//深度遍历 
void DFS(int index,int depth){//index是结点下标,depth是结点的深度 
	if(bt[index].weight!=0){//判断是否是retailer 
		int i;//循环计算变量 
		double temp = p;//临时变量 
//		for(i = 0;i< depth;i++){
//			 temp = temp*(1+r/100); 
//		} 
		temp = pow((1+r/100),depth) * temp;
		temp = temp*bt[index].weight;
		sum += temp;//计算总数 
	}
	int k; 
	for(k = 0;k < bt[index].child.size();k++ ){		
		DFS(bt[index].child[k],depth+1); 
	}
} 

int main(){
	int n;
	scanf("%d %lf %lf",&n,&p,&r);//输入信息
	int i,j;
	int number, cd;//number表示的是数字,cd表示的是孩子结点下标 
	for(i = 0;i< n;i++){
		scanf("%d",&number);			
		if(number != 0){
			bt[i].weight = 0;//将非retailer的结点重量初始化为0
			for(j = 0; j< number;j++){
				scanf("%d",&cd);		
				bt[i].child.push_back(cd);//加入到数组下标中 
			}
		}
		else{//是retailer,则输入囤货重量 
			scanf("%d",&bt[i].weight);
		} 		 
	}
	DFS(0,0);//深度遍历
	printf("%.1lf",sum); 
} 	

/**
10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0 7
2 6 1
1 8
0 9
0 4
0 3
*/
/**验证输出 
	for(i = 0;i < n;i++){
		printf("i = %d,",i); 
		if(bt[i].child.size() > 0){
			for(j = 0;j<bt[i].child.size();j++){
				printf("%d ", bt[i].child[j]);//输出孩子结点	
			}printf("\n");
		}
		else
		printf("weight = %d\n",bt[i].weight);//输出货物重量 		
	} 
**/

 
3.总结

(1)需要注意如果直接使用for循环来处理叶子结点的幂次方,可能会导致出现时间超时的问题,所以需要使用到C++中的pow()函数。

(2)本题时关于递归遍历树,思想很简单:如果遇到叶子结点,则计算值,如果非叶子结点,继续往下遍历。关键是递归的写法,可能会有一些同学不会使用递归,我的方法是先看别人的代码,然后自己跟着敲一遍,然后自己再默写一遍。如此反复即可掌握递归的写法。【前提是,了解递归的原理,如果连递归怎么实现的都不清楚的话,还是先弄懂理论,再实践会节省很多时间。】

4.补充

(1)下面给出关于C++中使用幂函数的代码

#include <stdio.h>
#include <math.h>

int main(){
	int result;
	result = pow(2,3); 
	printf("2^3 = %d\n",result);	
	
	double	re = pow(0.1,3);
	printf("0.1^3 = %lf\n",re);	
}

同样在C中也可以实现

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

int main(){
	int result;
	result = pow(2,3); 
	printf("2^3 = %d\n",result);	
	
	double	re = pow(0.1,3);
	printf("0.1^3 = %lf\n",re);	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说文科技

看书人不妨赏个酒钱?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值