需要用C++语言,谢谢
代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true)
{
int n = 0;
int count = 0;
cin >> n;
int* nodes = (int*)malloc(sizeof(int)*n);
for (int i = 1; i < n; i++)
{
int k = 0;
cin >> k;
cin >> k;
cin >> nodes[k - 1];
}
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
int max = 0;
int i_tmp = i;
int j_tmp = j;
while (true)
{
if (i_tmp == j_tmp)
{
count += max;
break;
}
else
{
if (i_tmp >= 2 * j_tmp)
{
if (max < nodes[i_tmp])
{
max = nodes[i_tmp];
}
if (i_tmp % 2 == 1)
{
i_tmp = (i_tmp - 1) / 2;
}
else
{
i_tmp /= 2;
}
}
else if (2 * i_tmp <= j_tmp)
{
if (max < nodes[j_tmp])
{
max = nodes[j_tmp];
}
if (j_tmp % 2 == 1)
{
j_tmp = (j_tmp - 1) / 2;
}
else
{
j_tmp /= 2;
}
}
else
{
if (max < nodes[i_tmp])
{
max = nodes[i_tmp];
}
if (i_tmp % 2 == 1)
{
i_tmp = (i_tmp - 1) / 2;
}
else
{
i_tmp /= 2;
}
if (max < nodes[j_tmp])
{
max = nodes[j_tmp];
}
if (j_tmp % 2 == 1)
{
j_tmp = (j_tmp - 1) / 2;
}
else
{
j_tmp /= 2;
}
}
}
}
}
}
cout << "sum is" << count << "\n\n";
}
return 0;
}