Electricals circuit are generally graphs, not trees. But a single non-self referencing logical expression is a tree, which what I think the question is about.
In this case, since it's a full binary tree, so this actually makes it easier to streamline.
You're given n = 4.
So (it looks like) you know you have n*2 = 8 inputs.
You can do this with
1 2 3 4 5 6 7 8 9 10 11
|
#include <vector>
// ...
int n;
cin >> n;
vector<int> inputs(2*n);
for (int i = 0; i < 2*n; i++)
{
cin >> inputs[i];
}
|
So now, you have all the inputs stored.
Next, you know that you now have n logic gates, and n - 1 lines left.
So, loop over the n gates on the first loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
for (int i = 0; i < n; i++)
{
string gate;
cin >> gate;
if (gate == "xor")
{
inputs[i] = inputs[2*i] ^ inputs[2*i+1];
}
else if (gate == "nand")
{
inputs[i] = ~(inputs[2*i] & inputs[2*i+1]);
}
}
|
You'd do this loop n-1 times, halving the inputs needed each time.
e.g. loop over n/2 inputs on the second line.
(You'll probably end up having a loop within a loop)
Try something out, then ask for more help and show what you've tried.
(or copy lastchance's code)