1090 Highest Price in Supply Chain (25 分)。dfs+求树高,树的静态写法

感觉自己傻了,读错题了,题目说S​root for the root supplier is defined to be −1,根结点的父亲是-1,一开始没有判断temp正负,搞了个数组段错误。发现之后决定把数组开大点,然后把根节点存到最后,让这个原本是根节点的节点变成-1的孩子,导致多了一层,答案一致不对!!!

int main(){
    
    
    cin>>N>>p>>r;
    for(int i=0;i<N;i++)
    {
    
    
        int temp;
        cin>>temp;
        if(temp!=-1)
           n[temp].child.push_back(i);
        else
           n[100001].child.push_back(i);
    }
    dfs(100001,p);
 

改成后

#include<bits/stdc++.h>
using namespace std;
int N,num=0;
struct node{
    
    
    vector<int> child;
    double price=0;
}n[100002];
double sum=0,p,r,start;
void dfs(int root,double price){
    
    
    if(root!=start)
        price=price*(1.0+r/100.0);
    if(n[root].child.size()==0){
    
    
        if(price>=sum)
        {
    
    
            n[root].price=price;
            sum=price;
        }
    }
    else{
    
    
        for(int i=0;i<n[root].child.size();i++)
            dfs(n[root].child[i],price);
    }
}
int main(){
    
    
    cin>>N>>p>>r;
    for(int i=0;i<N;i++)
    {
    
    
        int temp;
        cin>>temp;
        if(temp!=-1)
           n[temp].child.push_back(i);
        else
           start=i;
    }
    dfs(start,p);
    for(int i=0;i<N;i++)
    {
    
    
        if(n[i].price==sum)
            num++;
    }
    printf("%.2lf %d",sum,num);
    return 0;
}

这道题其实大众解法是本质是求树高,看看柳诺的:


#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int n, maxdepth = 0, maxnum = 0, temp, root;
vector<int> v[100010];
void dfs(int index, int depth) {
    
    
    if(v[index].size() == 0) {
    
    
        if(maxdepth == depth)
            maxnum++;         //如果最后有更高的也没关系,重置1即可
        if(maxdepth < depth) {
    
    
            maxdepth = depth;
            maxnum = 1;
        }
        return ;
    }
    for(int i = 0; i < v[index].size(); i++)
        dfs(v[index][i], depth + 1);
}
int main() {
    
    
    double p, r;
    scanf("%d %lf %lf", &n, &p, &r);
    for(int i = 0; i < n; i++) {
    
    
        scanf("%d", &temp);
        if(temp == -1)
            root = i;
        else
            v[temp].push_back(i);
    }
    dfs(root, 0);
    printf("%.2f %d", p * pow(1 + r/100, maxdepth), maxnum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835526/article/details/113703934