JOI2007本選 問題5@C++

#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

int gcm(int a, int b)
{
	if(a < 0) a = -a;
	if(b < 0) b = -b;
	while(b>0) {
		int tmp = a % b;
		a = b;
		b = tmp;
	}
	return a;
}

class stick
{
public:
	int len0;
	int len1;
	stick *child0;
	stick *child1;
	stick *parent;
	int min_weight()
	{
		int weight0 = 1;
		if(child0 != NULL) {
			weight0 = child0->min_weight();
		}
		int weight1 = 1;
		if(child1 != NULL) {
			weight1 = child1->min_weight();
		}
		int moment0 = weight0 * len0;
		int moment1 = weight1 * len1;
		int moment_gcm = gcm(moment0, moment1);
		int mul0 = moment1 / moment_gcm;
		int mul1 = moment0 / moment_gcm;
		return weight0 * mul0 + weight1 * mul1;
	}
	stick() : len0(0), len1(0), child0(NULL), child1(NULL), parent(NULL)
	{
		
	}
	~stick()
	{
		
	}
};

int main(int argc, char *argv[], char *envp[])
{
	#ifdef DEBUG
	FILE *in = stdin;
	FILE *out = stdout;
	#else
	FILE *in = fopen("input.txt", "r");
	FILE *out = fopen("output.txt", "w");
	#endif
	int n;
	fscanf(in, "%d\n", &n);
	vector<stick> sticks(n);
	for(int i=0;i<n;i++) {
		int p;
		int q;
		int r;
		int b;
		fscanf(in, "%d %d %d %d\n", &p, &q, &r, &b);
		sticks[i].len0 = p;
		sticks[i].len1 = q;
		if(r != 0) {
			sticks[i].child0 = &sticks[r-1];
			sticks[r-1].parent = &sticks[i];
		}
		if(b != 0) {
			sticks[i].child1 = &sticks[b-1];
			sticks[b-1].parent = &sticks[i];
		}
	}
	stick *root = &sticks[0];
	while(root->parent != NULL) {
		root = root->parent;
	}
	fprintf(out, "%d\n", root->min_weight());
	fclose(in);
	fclose(out);
	return 0;
}