L2-020. 功夫传人
用了一个vector容器,具体参考C++函数库
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
double z,r,sum=0,people[100005];//得道者
vector<int> v[100005];
int f(int k,double w)
{
if (people[k]!=0)
sum+=w*people[k];
else
{
for (int i=0;i<v[k].size();i++)
f(v[k][i],w*r);
}
}
int main()
{
memset(people,0,sizeof(people));
int i,j,n,m,temp;
sum=0;
cin>>n>>z>>r;
r=1-r/100;
for (i=0;i<n;i++)
{
cin>>m;
if (m==0)
cin>>people[i];
else
{
for (j=0;j<m;j++)
{
cin>>temp;
//将temp存入容器V中。
v[i].push_back(temp);
}
}
}
f(0,z);//开始查找得道者
printf("%d",(int )sum);
}
vector里面嵌套一个set,递归实现
#include<iostream>
#include<cstring>
#include<set>
#include<vector>
#include<cmath>
using namespace std;
int n,people[100005];
double r,z,sum=0;
vector<set<int> >V;
int dfs(int k,double r)
{
if (people[k]!=0)
{
sum+=r*people[k];
return 0;
}
for (auto i=V[k].begin();i!=V[k].end();i++)
dfs(*i,r*z);
}
int main()
{
int i,j,t,temp;
memset(people,0,sizeof(people));
cin>>n>>r>>z;
z=1-z/100;
for (i=0;i<n;i++)
{
cin>>t;
set<int>S;
for (j=0;j<t;j++)
{
cin>>temp;
S.insert(temp);
}
V.push_back(S);
if (t==0)
{
cin>>temp;
people[i]=temp;
}
}
dfs(0,r);
printf("%.0lf",floor(sum));
}