思路
题意就是求一棵树的高度,只需要一次bfs即可。
时间复杂度为O(n),这题n的范围是小于n<=10^5,可以通过这个题。
你的代码确实很乱,而且思路不够清晰,请对照我的代码,看我有哪些优化的地方。
有问题可以评论或私信。
AC代码
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 100000 + 5;
vector G[maxn];
int lenth[maxn]; //根结点到每个节点的长度
int bfs(int root) {
int maxTran = 0;
memset(lenth, -1, sizeof(lenth));
queue Q;
Q.push(root);
lenth[root] = 0;
while(!Q.empty()) {
int supp = Q.front(); Q.pop();
for(int i = 0; i < G[supp].size(); i++) {
int buy = G[supp][i];
lenth[buy] = lenth[supp] + 1;
Q.push(buy);
maxTran = max(maxTran, lenth[buy]);
}
}
return maxTran;
}
int main() {
int n;
double p, r;
while(scanf("%d %lf %lf", &n, &p, &r) == 3) {
for(int i = 0; i < n; i++) {
G[i].clear();
}
int supp, root;
for(int i = 0; i < n; i++) {
scanf("%d", &supp);
if(supp != -1) {
G[supp].push_back(i);
} else {
root = i;
}
}
// 树的高度
int maxTran = bfs(root);
double highPrice = p;
for(int i = 0; i < maxTran; i++) {
highPrice *= (1 + r / 100);
}
// 计算取得最高price的人数
int cnt = 0;
for(int i = 0; i < n; i++) {
if(lenth[i] == maxTran) cnt++;
}
printf("%.2f %d\n", highPrice, cnt);
}
return 0;
}