1090 Highest Price in Supply Chain (25)(25 分)

很简单的DFS,找最深的节点

#include<iostream>
#include<vector>
using namespace std;
const int maxn = 1e5 + 10;
struct node {
    double p;
    vector<int>child;
}Node[maxn];
int n;
double p, r;
double maxp = 0;
int cnt;
void DFS(int root)
{
    if (Node[root].child.size() == 0)
    {
        if (Node[root].p > maxp)maxp = Node[root].p, cnt = 1;
        else if (Node[root].p == maxp)cnt++;
        return;
    }
    for (int i = 0; i < Node[root].child.size(); i++)
    {
        int child = Node[root].child[i];
        Node[child].p = Node[root].p*(1 + r);
        DFS(child);
    }
}
int main()
{
    int root = 0;
    scanf("%d%lf%lf", &n, &p, &r);
    r /= 100;
    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d", &x);
        if (x == -1)root = i;
        else
            Node[x].child.push_back(i);
    }
    Node[root].p = p;
    DFS(root);
    printf("%.2f %d", maxp, cnt);
    return 0;
}

BFS解法:

void BFS(int root)
{
    queue<int>q;
    q.push(root);
    while (!q.empty())
    {
        int top = q.front();
        q.pop();
        if (Node[top].child.size())
        {
            for (int i = 0; i < Node[top].child.size(); i++)
            {
                int child = Node[top].child[i];
                Node[child].p = Node[top].p*(1 + r);
                q.push(child);
            }
        }
        else
        {
            if (Node[top].p > maxp)maxp = Node[top].p, cnt = 1;
            else if (Node[top].p == maxp)cnt++;
        }
    }
}

可以不用设置结构体,直接遍历即可

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
vector<int>a[maxn];
int n;
double P,r;
int maxheight;
vector<int>ans; 
void DFS(int v,int height)
{
    if(a[v].size()==0)
    {
        if(height>maxheight)
        {
            maxheight=height;
            ans.clear();
            ans.push_back(v);
        }
        else if(height==maxheight)ans.push_back(v);
        return;
    }
    for(int i=0;i<a[v].size();i++)
    {
        int u=a[v][i];
        DFS(u,height+1);
    }
} 
int main()
{
    scanf("%d%lf%lf",&n,&P,&r);
    r/=100;
    int root;
    for(int i=0;i<n;i++)
    {
        int x;
        scanf("%d",&x);
        if(x!=-1)a[x].push_back(i);
        else root=i;
    }
    DFS(root,1);
    printf("%.2f %d",P*pow(1+r,maxheight-1),ans.size());
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,867评论 0 33
  • 各校历年复试机试试题 清华、北大、华科试题详细笔记部分,少笔记部分与少数leetcode【含个人整理笔记】 一、详...
    AIM外星人阅读 1,314评论 0 1
  • 从未想过一个符号或是一个标记;一段音乐或是一个片断;一个微笑或是一个背影,当这一切从在你脑中交替的闪过的时候,一种...
    简桀阅读 208评论 0 0
  • 第三章:麻辣五年(三国时代初期) 嗯,终于婆媳姑碰到一起了。来,我们看看当时各自的人格特点、战斗方式以及战斗力指数...
    娟姐的心语话廊阅读 816评论 10 10
  • 我不曾熟悉爱因斯坦神秘而晦涩难懂的相对论,但是当我听到这样一个令人充满遐思的题目,默默思考了很久,是不是相对的快乐...
    查理安阅读 559评论 0 2

友情链接更多精彩内容