pzhang.pn
BAN USER#include <iostream>
using namespace std;
int findWay(int amount, int den[], int maxDen)
{
if (maxDen == 0) return 1;
int sum = 0;
for (int i = amount/den[maxDen]; i>=0; i--)
sum += findWay(amount-(i*den[maxDen]), den, maxDen-1);
return sum;
}
int main() {
int myDen[3] = {1, 2, 3};
cout<<"There are "<<findWay(5, myDen, 2)<<" ways."<<endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int id;
int parent;
int weight;
// ... can add other fields right here, if necessary
int totalWeight; // a total weight of self and all the sub tree.
Node(int id_, int parent_, int weight_)
{
id = id_; parent = parent_; weight = weight_; totalWeight = 0;
}
};
void printSubTreeWeight(vector<Node> nodes) {
int ct; // current index
bool haveParent;
for (int i=0; i<nodes.size(); i++)
{
ct = i;
haveParent = false;
do
{
haveParent = false;
nodes[ct].totalWeight += nodes[i].weight;
if (nodes[ct].parent!=0)
{
//current = findIndexByID(nodes[ct].parent);
for (int j=0; j<nodes.size(); j++)
{
if (nodes[j].id == nodes[ct].parent)
{
ct = j;
haveParent = true;
}
}
}
}while (haveParent);
}
for (int i=0; i<nodes.size(); i++)
{
cout<<"id="<<nodes[i].id<<" Parent="<<nodes[i].parent<<" W="<<nodes[i].weight<<" total="<<nodes[i].totalWeight<<endl;
}
}
int main()
{
vector<Node> nodes;
//Node n = new Node(10,30,1);
nodes.push_back(Node(10,30,1));
nodes.push_back(Node(30,0,10));
nodes.push_back(Node(20,30,2));
nodes.push_back(Node(50,40,3));
nodes.push_back(Node(40,30,4));
printSubTreeWeight(nodes);
}
and the output is
id=10 Parent=30 W=1 total=1
id=30 Parent=0 W=10 total=20
id=20 Parent=30 W=2 total=2
id=50 Parent=40 W=3 total=3
id=40 Parent=30 W=4 total=7
}
- pzhang.pn October 29, 2014