这三题的考察点都是普通树的遍历,可以使用BFS和DFS
用DFS写代码量可能更小…不过BFS很好理解。
做题的时候一定要判断好是二叉树还是可能有很多孩子的普通树。
三题都差不多 所以直接上代码了
DFS之 A1090 vs A1094
1090这题只需要用到叶子结点,所以在递归边界(叶子结点)的时候进行变量操作
1094则是单纯地利用DFS遍历,然后计数,因此每递归一次只需要增加相应数量就行,直到全部搜索完。
文章目录
A1079 Total Sales of Supply Chain(BFS做法)
#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int N;
double P,r;
double total=0;
struct Node
{
double product;
double rate;
vector<int> child;
}node[maxn];
void BFS()
{
queue<int> q;
q.push(0);
while(!q.empty())
{
int top=q.front();
q.pop();
for(int i=0;i<node[top].child.size();i++)
{
int k=node[top].child[i];
q.push(k);
node[k].rate=(1+0.01*r)*node[top].rate;
}
}
}
int main()
{
scanf("%d%lf%lf",&N,&P,&r);
for(int i=0;i<N;i++)
{
int k;
node[i].rate=P;
node[i].product=0;
scanf("%d",&k);
if(k!=0)
{
for(int j=0;j<k;j++)
{
int t;
scanf("%d",&t);
node[i].child.push_back(t);
}
}
else if(k==0)
{
scanf("%lf",&node[i].product);
}
}
BFS();
for(int i=0;i<N;i++)
{
total+=node[i].product*node[i].rate;
}
printf("%.1f",total);
}
A1090 Highest Price in Supply Chain(DFS做法)
#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int N;
double P,r,total;
int maxDepth=0;
int maxNum=0;
struct Node
{
vector<int> child;
}node[maxn];
void DFS(int index,int depth)
{
if(node[index].child.size()==0)
{
if(depth>maxDepth)
{
maxDepth=depth;
maxNum=1;
}
else if(depth==maxDepth)
{
maxNum++;
}
return;
}
for(int i=0;i<node[index].child.size();i++)
{
DFS(node[index].child[i],depth+1);
}
}
int main()
{
scanf("%d%lf%lf",&N,&P,&r);
int root;
int parent;
for(int i=0;i<N;i++)
{
scanf("%d",&parent);
if(parent==-1) root=i;
else node[parent].child.push_back(i);
}
DFS(root,0);
double maxPrice=P;
for(int i=0;i<maxDepth;i++)
{
maxPrice*=(1+0.01*r);
}
printf("%.2f %d",maxPrice,maxNum);
}
A1094 The Largest Generation(DFS做法)
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int n,m,num[105]={0};
// num[i]记录第i-level的人数,i代表第i代
struct Node
{
vector<int> child;
}node[maxn];
void DFS(int index,int depth)
{
num[depth]++;
for(int i=0;i<node[index].child.size();i++)
{
DFS(node[index].child[i],depth+1);
}
}
int main()
{
scanf("%d%d",&n,&m);
int root=1;
for(int i=1;i<=m;i++)
{
int parent,k;
scanf("%d%d",&parent,&k);
for(int j=0;j<k;j++)
{
int childj;
scanf("%d",&childj);
node[parent].child.push_back(childj);
}
}
DFS(root,1);
int max=1,maxi=1;
for(int i=1;i<=n;i++)
{
if(num[i]>max)
{
max=num[i];
maxi=i;
}
}
printf("%d %d",max,maxi);
}