1079. Total Sales of Supply Chain (25)

题目地址:http://www.patest.cn/contests/pat-a-practise/1079

此题采用queue 和 map 求每一个节点的层数,并统计,叶子层的总数,注意n==1的特殊情况(否则扣一分),很容易ac

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <unordered_map>
#include <algorithm>

using namespace std;

#define N 100002

int n;
double p, r;

vector<int> a[N];

unordered_map<int, int> um; // 节点i 的数量 映射
unordered_map<int, int> um2; // 层次i 的总数量 映射

int cengci[N];
double price[N];

void func()
{
    queue<int> que;
    que.push(0);
    cengci[0] = 0;
    int i;
    while (!que.empty())
    {
        int nowC = que.front();
        que.pop();
        int Lenc = a[nowC].size();
        for (i = 0; i < Lenc; i++)
        {
            int nextC = a[nowC][i];
            cengci[nextC] = cengci[nowC] + 1;
            if ((int)(a[nextC].size()) > 0)
            {
                que.push(nextC);
            }
            else{
                um2[cengci[nextC]] += um[nextC];
            }
        }
    }
    double sum = 0;
    unordered_map<int, int>::iterator it;
    for (it = um2.begin(); it != um2.end(); it++)
    {
        int cengshu = it->first;
        int amout = it->second;
        sum += price[cengshu] * amout;
    }
    printf("%.1lf",sum);
}

int main()
{
    //freopen("in", "r", stdin);
    int i, j;
    scanf("%d", &n);
    scanf("%lf%lf", &p, &r);

    price[0] = p;
    for (i = 1; i <= n; i++)
    {
        price[i] = price[i - 1] * (1 + r / 100);
    }
    int k, tmp;
    if (n == 1) // 就只有根的情况单独讨论要 , 否则case2出错
    {
        scanf("%d%d", &k, &tmp);
        printf("%.1lf", price[0] * tmp);
        return 0;
    }

    for (i = 0; i < n; i++)
    {
        scanf("%d", &k);
        if (k == 0)
        {
            scanf("%d", &tmp);
            um[i] = tmp;
        }
        else{
            for (j = 0; j < k; j++)
            {
                scanf("%d", &tmp);
                a[i].push_back(tmp);
            }
        }
    }
    func();
    printf("\n");
    return 0;
}

你可能感兴趣的:(1079. Total Sales of Supply Chain (25))