题目
思路
题目大意:找到最便宜的零售商以及这样零售商的数量,也就是最早出现叶节点的那一层中叶节点个数;
最好用BFS,可以不用全部遍历,比较高效,也可以用DFS,但是需要全部遍历一遍;
一层层的遍历,遍历每一层时设置一个布尔值,用来判断这层有没有叶节点,如果出现叶节点,那么在遍历完这层后就应该结束迭代;
为什么不是一找到叶节点就结束迭代,因为需要统计这层叶节点的个数;
代码
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
const int maxn = 1e5 + 5;
struct node{
vector<int> child;
}Node[maxn];
struct Ele{
int id, depth;
}ele;
int num = 0, n;
double p, r, sum;
void BFS(int id, int depth){
queue<Ele> Q;
ele.id = id, ele.depth = depth;
Q.push(ele);
while(!Q.empty()){
int k = Q.size();
bool flag = false;//标记这一层有没有叶节点,如果有则结束迭代
for(int i = 0; i < k; i ++){
Ele top = Q.front();
Q.pop();
//如果碰到叶节点
if(Node[top.id].child.size() == 0){
sum = p * pow(1 + r, top.depth);
flag = true;
num ++;
}
else{
//否则把每个孩子节点放进去
for(int j = 0; j < Node[top.id].child.size(); j ++){
ele.id = Node[top.id].child[j];
ele.depth = top.depth + 1;
Q.push(ele);
}
}
}
//如果刚刚这一层有叶节点则退出
if(flag == true) break;
}
}
int main()
{
scanf("%d%lf%lf", &n, &p, &r);
r /= 100;
int k, t;
for(int i = 0; i < n; i ++){
scanf("%d", &k);
for(int j = 0; j < k; j ++){
scanf("%d", &t);
Node[i].child.push_back(t);
}
}
BFS(0, 0);
printf("%.4f %d", sum, num);
system("pause");
return 0;
}