PAT(甲级)1106 Lowest Price in Supply Chain (25point(s))

题目

题目链接

思路

题目大意:找到最便宜的零售商以及这样零售商的数量,也就是最早出现叶节点的那一层中叶节点个数;
最好用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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值