PAT Class A 1079 (C++)

There is no problem with test points 2, 3, and 5: After online investigation, it is found that the accuracy of calculation results using float is not enough, just change it to double

Test point 6 timed out at the beginning, when the code:

#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
vector<int>father;
vector <int> is_retailer;
int times;double sum;
double price, rate;
void dps(int end,int now) {
	if (father[now] == -1) {
		sum += is_retailer[end] * price * pow(1 + rate / 100, times);
		return;
	}
	times++;
	dps(end, father[now]);
}
int main() {
	int N; cin >> N;
	cin >> price >> rate;
	father.resize(N,-1);
	is_retailer.resize(N,-1);
	for (int i = 0; i < N; i++) {
		int number; cin >> number;
		for (int j = 1; j <= number; j++) {
			int child; cin >> child;
			father[child] = i;
		}
		if (number == 0) cin >> is_retailer[i];
	}
	sum = 0;
	for (int i = 0; i < N; i++) {
		if (is_retailer[i] != -1) {
			times = 0;
			dps(i, i);
		}
	}
	printf("%.1lf", sum);
	return 0;
}

Then I took a little look at the idea of ​​this link: PAT Class A 1079_Blue Sky-CSDN Blog

The AC codes are as follows:

#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
vector<int>children;
vector <int> is_retailer;
vector<int>layer;
double sum,price, rate;
void update(int father) {
	if(children[father]==-1) return;
	layer[children[father]] = layer[father] + 1;
	update(children[father]);
}
int main() {
	int N; cin >> N;
	cin >> price >> rate;
	children.resize(N,-1);
	is_retailer.resize(N,-1);
	layer.resize(N, 0);
	for (int i = 0; i < N; i++) {
		int number; cin >> number;
		for (int j = 1; j <= number; j++) {
			int child; cin >> child;
			children[i] = child;
			layer[child] = layer[i] + 1;
			update(child);
		}
		if (number == 0) cin >> is_retailer[i];
	}
	sum = 0;
	for (int i = 0; i < N; i++) {
		if (is_retailer[i] != -1) 
			sum += is_retailer[i] * price * pow(1 + rate / 100, layer[i]);
	}
	printf("%.1lf", sum);
	return 0;
}

Compared with the code before the change, the path taken by dps to update the number of layers is shorter, and all the paths must be completed before the change.

Guess you like

Origin blog.csdn.net/weixin_45681165/article/details/121108278