1090. Highest Price in Supply Chain (25)-dfs求层数

给出一棵树,在树根出货物的价格为p,然后每往下一层,价格增加r%,求所有叶子节点中的最高价格,以及该层叶子结点个数。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <cmath>
/*
相当于求解树的层数
*/
using namespace std;
const int maxn=100000+5;
int maxlayer=0,num=0;
int head[maxn];
int tot;

struct Edge{
    int to;
    int next;
}edge[maxn];

void init(){
    tot=0;
    memset(head,-1,sizeof(head));
}
void add(int u,int v){
    edge[tot].next=head[u];
    edge[tot].to=v;
    head[u]=tot++;
}
void dfs(int u,int layer){
    if(head[u]==-1){
        if(layer>maxlayer){
            maxlayer=layer;
            num=1;
        }
        else if(layer==maxlayer)
            num++;
        return;
    }
    for(int k=head[u];k!=-1;k=edge[k].next){
        int v=edge[k].to;
        dfs(v,layer+1);
    }
}


int main()
{
    int v,root;
    int n;
    double p,r;
    scanf("%d %lf %lf",&n,&p,&r);
    init();
    for(int i=0;i<n;i++){
        scanf("%d",&v);
        if(v==-1)
            root=i;
        else
            add(v,i);
    }
    dfs(root,0);
    double ans=p*pow(1+r/100,maxlayer);
    printf("%.2lf %d",ans,num);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/chenxiwenruo/p/6388849.html