1079 total sales of supply chain

BFS,用递归的话会段错误,改用vector,变量idx记录下一层的起点

AC代码:

#include <vector>
#include <cstdio>
#include <map>
using namespace std;
/*void bfs(vector<vector<int>>& g,vector<int> currentLayer,double p,double r,map<int,int>& amount,double& sum,double& r0){
    vector<int> next;
    for(int i = 0;i < currentLayer.size();i++){
        if(g[currentLayer[i]].size() == 0){
            sum += p * r * amount[currentLayer[i]];
        }
        else{
            for(int j = 0;j < g[currentLayer[i]].size();j++){
                next.push_back(g[currentLayer[i]][j]);
            }
        }
    }
    if(next.size() != 0)
        bfs(g,next,p,r*(1+r0),amount,sum,r0);
}*/
int main(){
    int n;
    double p,r;
    scanf("%d %lf %lf",&n,&p,&r);
    r /= 100.0;
    vector<vector<int>> g(n);
    map<int,int> amount;
    for(int i = 0;i < n;i++){
        int k;
        scanf("%d",&k);
        if(k == 0){
            scanf("%d",&amount[i]);
        }
        else{
            for(int j = 0;j < k;j++){
                int son;
                scanf("%d",&son);
                g[i].push_back(son);
            }
        }
    }
    double sum(0.0);
    vector<int> currentLayer;
    currentLayer.push_back(0);
    //bfs(g,currentLayer,p,1,amount,sum,r);
    vector<int> v;
    int idx(0);
    double rp(1);
    v.push_back(0);
    while(true){
        int nextId(v.size());
        bool flag(false);
        for(int i = idx;i < nextId;i++){
            if(g[v[i]].size() == 0){
                sum += p * rp * amount[v[i]];
            }
            else{
                flag = true;
                for(int j = 0;j < g[v[i]].size();j++){
                    v.push_back(g[v[i]][j]);
                }
            }
        }
        rp *= (1 + r);
        if(!flag)
            break;
        idx = nextId;
    }
    printf("%.1lf\n",sum);
    return 0;
}

 

你可能感兴趣的:(1079 total sales of supply chain)