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

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

#include
#include
using namespace std;
const int maxn = 1e5 + 10;
struct node {
    double p;
    vectorchild;
}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)
{
    queueq;
    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
using namespace std;
const int maxn=1e5+10;
vectora[maxn];
int n;
double P,r;
int maxheight;
vectorans; 
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

你可能感兴趣的:(1090 Highest Price in Supply Chain (25)(25 分))