PAT 1079. Total Sales of Supply Chai (dfs)

很简单的,从供应商0处dfs一遍即可。


#include <cstdio>
#include <list>

using namespace std;

struct People
{
	double m_need;
	double m_price;
	list<int> m_child;
};

int n, k, num;
double p, r, need;
People people[100010];
double sum = 0;

void dfs(int now)
{
	People p = people[now];
	if (p.m_child.size() == 0)
	{
		sum += p.m_need * p.m_price;
		return ;
	}
	for (auto it = p.m_child.begin(); it != p.m_child.end(); ++ it)
	{
		people[*it].m_price = p.m_price * (1+r/100);
		dfs( *it );
	}
}

int main()
{
	scanf("%d%lf%lf", &n, &people[0].m_price, &r);
	for (int i = 0; i < n; ++ i)
	{
		scanf("%d", &k);
		if (k == 0)
		{
			scanf("%lf", &need);		
			people[i].m_need = need;
		}
		for (int j = 0; j < k; ++ j)
		{
			scanf("%d", &num);
			people[i].m_child.push_back(num);
		}
	}
	dfs(0);

	printf("%.1lf\n", sum);

	return 0;
}



你可能感兴趣的:(C++,DFS,pat)