Loading Similar Posts
> O(log(i) + log(j))
where i is the value on heated photon and j is value on emitting photon.
long long par(long long node){ // find and return parent
if(node&1) node-=1;
return (node>>1);
}
long long find_level(long long node)
{
long long root =1;
while((root<<1)<=node) root<<=1;
return root;
}
int find_dis(long long i, long long j){
int ans = -1;
if(i>j) swap(i,j);
long long level_of_i = find_level(i); // to find the minimum power of two which is just smaller or equal to node
while(par(j)>=level_of_i){
ans-=1;
j = par(j);
}
while(i!=j){
ans-=2;
i = par(i);
j = par(j);
}
return ans;
}
Overview
Approach
First, we will have to convert infix to postfix format. We will do this using a stack.
Then we will evaluate this postfix expression.
Time Complexity
O(n)
as each element of the string would be inserted and removed from the stack a constant number of times.PseudoCode
if(isnumber(s)){
values.push(stoi(s));
}
else if(s=="("){
ops.push(s);
}
else if(s == ")"){
while(!ops.empty() && ops.top() != "(")
{
int firstval=values.top();
int secondval = values.top();
values.pop();
values.pop();
string op = ops.top();
ops.pop();
int result=eval(firstval,secondval,op);
values.push(result);
}
if(!ops.empty())
ops.pop();
}
else {
int firstval=values.top();
int secondval = values.top();
values.pop();
values.pop();
string op = ops.top();
ops.pop();
int result=eval(firstval,secondval,op);
values.push(result);
}
// To evaluate the postfix expression
while(!operators.empty()){
int secondval = values.top();
values.pop();
int firstval = values.top();
values.pop();
string operator = operators.top();
operators.pop();
int result=eval(firstval,secondval,operator);
values.push(result);
}
// final value in stack is the answer
int rec(int i, int mask, int N, int K, vector<int>&to_dec, vector<int>&cost) {
if (i == N) {
if (mask == ((1 << K) - 1))return 0;
else return INF;
}
if (dp.find({i, mask}) != dp.end())return dp[ {i, mask}];
int op1 = cost[i] + rec(i + 1, mask | to_dec[i], N, K, to_dec, cost); // first option is to include current string
int op2 = rec(i + 1, mask, N, K, to_dec, cost); // second option not to include
return dp[ {i, mask}] = min(op1, op2);
}
Time Complexity: O(N*K), N
is the number of types of candy combos and K is the different flavors of candles.
Is it possibe to solve it through iteration without recursion??