很简单的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;
}