题目
https://pintia.cn/problem-sets/994805342720868352/problems/994805362341822464
题意
题目给出供应链也就是一棵树,下标0为树根,树根对应的价格为P。每向下一层,价格便会提升r%。题目最终要求出最低的价格以及其对应的零售商个数,翻译一下就是求最浅的层以及该层的叶子节点个数。
代码解析
本人
将数据读入f后,通过dfs寻找根节点,并用cnt存储对应深度的根节点数量,通过比较确定最小的depth
参考
其它相同,变化的是维护的不再是一个整型数字加数组,而是两个整型数字,维护效率更高(通过比较二者的运行时间可得出该结论),因此该方案更优
AC代码
本人代码
#include<bits/stdc++.h>
using namespace std;
//vector<int> f[100005];
unordered_map<int,vector<int>> f;
map<int,int> cnt;
int minn=INT_MAX;
void dfs(int root,int depth)
{
if(minn<depth)
return;
if(f[root].size()==0)
{
cnt[depth]++;
if(depth<minn) minn=depth;
}
for(int i=0;i<f[root].size();i++)
dfs(f[root][i],depth+1);
}
int main()
{
int n;
double p,r;
cin>>n>>p>>r;
r=r/100+1;
for(int i=0;i<n;i++)
{
int t,tmp;
cin>>t;
while(t--)
{
cin>>tmp;
f[i].push_back(tmp);
}
}
dfs(0,0);
printf("%.4lf %d",p*pow(r,minn),cnt[minn]);
}
参考代码
#include<bits/stdc++.h>
using namespace std;
vector<int> f[100005];
map<int,int> cnt;
int mindepth=INT_MAX,minnum=1;
void dfs(int root,int depth)
{
if(mindepth<depth)
return;
if(f[root].size()==0)
{
if(mindepth==depth)
minnum++;
else if(mindepth>depth)
{
mindepth=depth;
minnum=1;
}
}
for(int i=0;i<f[root].size();i++)
dfs(f[root][i],depth+1);
}
int main()
{
int n;
double p,r;
cin>>n>>p>>r;
r=r/100+1;
for(int i=0;i<n;i++)
{
int t,tmp;
cin>>t;
while(t--)
{
cin>>tmp;
f[i].push_back(tmp);
}
}
dfs(0,0);
printf("%.4lf %d",p*pow(r,mindepth),minnum);
}
注意
f的定义可以写作
vector<int> f[100005];
或者
unordered_map<int,vector<int>> f;
但如果写做map<int,vector> f,则会有两个测试点报段错误,分析原因是爆栈了(unordered_map是无序的,存储时更节省空间)
参考
1106. Lowest Price in Supply Chain (25)-PAT甲级真题(dfs,bfs,树的遍历)