强烈推荐,刷PTA的朋友都认识一下柳神–PTA解法大佬
本文由参考于柳神博客写成
还有就是非常非常有用的 算法笔记 全名是
算法笔记 上级训练实战指南 //这本都是PTA的题解
算法笔记
PS 今天也要加油鸭
题目原文
A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.
Starting from one root supplier, everyone on the chain buys products from one’s supplier in a price P and sell or distribute them in a price that is r% higher than P. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.
Now given a supply chain, you are supposed to tell the highest price we can expect from some retailers.
Input Specification:
Each input file contains one test case. For each case, The first line contains three positive numbers: N (≤105), the total number of the members in the supply chain (and hence they are numbered from 0 to N−1); P, the price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then the next line contains N numbers, each number S**i is the index of the supplier for the i-th member. Sroot for the root supplier is defined to be −1. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the highest price we can expect from some retailers, accurate up to 2 decimal places, and the number of retailers that sell at the highest price. There must be one space between the two numbers. It is guaranteed that the price will not exceed 1010.
Sample Input:
9 1.80 1.00
1 5 4 4 -1 4 5 3 6
Sample Output:
1.85 2
生词如下:
不太有,都看懂了.因为这题和1079蛮像的.结果也都差不多,就改几句代码就OK了.用的还是柳神的板子
思路如下:
就是DFS深度一起过一遍.然后加几个if判断语句.找出最长的长度有没有相同的.
还有算出深度.
代码如下:
#include<iostream>
#include <vector>
#include <cmath>
using namespace std;
struct node {
int data;
int level;
vector<int> child;
};
vector<node> v;
int result=0,ans=0;
int dfs(int index,int depth) {
if (v[index].child.size() == 0) return depth;
for (int i = 0; i < v[index].child.size(); i++) {
if (depth + 1 > result) {
result = depth+1;
ans = 0;
}
else if (depth + 1 == result) ans++;
dfs(v[index].child[i], depth + 1);
}
}
int main() {
int n,root=0;
double p, r;
scanf("%d%lf%lf", &n, &p, &r);
v.resize(n);
for (int i = 0; i < n; ++i) {
scanf("%d",&v[i].data);
if (v[i].data == -1) root = i;
else v[v[i].data].child.push_back(i);
}
dfs(root,0);
printf("%.2lf %d",p*pow((1+r/100.0), result),ans+1);
return 0;
}
柳神的思路和我的一模一样,就不贴了.
但是有趣的是.
柳神的代码中比我的好的地方贴一下.
柳神的代码
void dfs(int index, int depth) {
if(v[index].size() == 0) {
if(maxdepth == depth)
maxnum++;
if(maxdepth < depth) {
maxdepth = depth;
maxnum = 1;
}
return ;
}
for(int i = 0; i < v[index].size(); i++)
dfs(v[index][i], depth + 1);
}
他的比较是在==0 哪里写的,这样可以少比较很多次.
比我的代码要好.
总结
树的遍历.这个可以算是模板了.
需要的东西在向上加.
非常的好用的模板.
要学会灵活的改
自己的小错误还是太多了,导致我改了不少时间.
如果这篇文章对你有张帮助的话,可以用你高贵的小手给我点一个免费的赞吗
相信我,你也能变成光.
如果你有任何建议,或者是发现了我的错误,欢迎评论留言指出.