PAT A1079 Total Sales of Supply Chain
Sample Input:
~~10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0 7
2 6 1
1 8
0 9
0 4
0 3
Sample Output:
42.4
word | meaning |
---|---|
increment | n. 增长 |
- 思路 1:
- 根据题意建树(静态表示),每个节点的product都初始化为0,方便计算
- 层序遍历树,每一层元素的rate赋值为上层rate*(1+r/100),对所有出队元素累加product*rate即可,因为初始化0,只有叶子(retailer)会累加上(也可以通过判断出队元素的child是否为空,来决定是否累加)
- code 1:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100010;
int n;
double p, r; //r比率 r%
struct Per{
int pro;
double rate;
vector<int> child;
Per(){ pro = 0; }
}per[maxn];
double ans = 0;
void levelOrder(){
queue<int> q;
q.push(0);
per[0].rate = p;
while(!q.empty()){
int now = q.front();
ans += per[now].rate * per[now].pro;
q.pop();
for(int i = 0; i < per[now].child.size(); ++i){
int child = per[now].child[i];
per[child].rate = per[now].rate * (1.0 + r / 100.0);
q.push(child);
}
}
}
int main(){
scanf("%d %lf %lf", &n, &p, &r);
for(int i = 0; i < n; ++i){
int nc, tmp;
scanf("%d", &nc);
if(nc != 0){
for(int j = 0; j < nc; ++j){
scanf("%d", &tmp);
per[i].child.push_back(tmp);
}
}else{
scanf("%d", &per[i].pro);
}
}
levelOrder();
printf("%.1f", ans);
return 0;
}
-
思路 2:
DFS:递归边界:结点没有孩子(即叶子结点,对应的rate = p * (1+r/100)^depth //depth从0开始) -
code 2:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n;
double p, r; //r比率 r%
struct Per{
int pro;
vector<int> child;
}per[maxn];
double ans = 0;
void DFS(int idex, int depth){
if(per[idex].child.size() == 0){
ans += 1.0 * per[idex].pro * p * pow(1+r, depth);
return;
}
for(int i = 0; i < per[idex].child.size(); ++i){
int child = per[idex].child[i];
DFS(child, depth+1);
}
}
int main(){
scanf("%d %lf %lf", &n, &p, &r);
r /= 100;
for(int i = 0; i < n; ++i){
int nc, tmp;
scanf("%d", &nc);
if(nc != 0){
for(int j = 0; j < nc; ++j){
scanf("%d", &tmp);
per[i].child.push_back(tmp);
}
}else{
scanf("%d", &per[i].pro);
}
}
DFS(0, 0);
printf("%.1f", ans);
return 0;
}
- T2 code: DFS,直接用二维vector存树
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
unordered_map<int, double> prod;
vector<int> node[maxn];
double sum = 0.0;
void DFS(int id, double p, double r){
if(node[id].size() == 0){
sum += prod[id] * p;
return;
}
for(int i = 0; i < node[id].size(); ++i){
int nex = node[id][i];
DFS(nex, p * r , r);
}
}
int main(){
int n;
double p, r;
scanf("%d %lf %lf", &n, &p, &r);
for(int i = 0; i < n; ++i){
int k, tmp;
scanf("%d", &k);
if(k == 0){
scanf("%d", &tmp);
prod[i] = tmp;
}else{
for(int j = 0; j < k; ++j){
scanf("%d", &tmp);
node[i].push_back(tmp);
}
}
}
DFS(0, p, r * 0.01 + 1); // Wrong 1: 脑抽开始写成 1.01 * r ( != 0.01 * r + 1)
printf("%.1lf\n", sum);
return 0;
}