This is a search problem that can be solved using brutal force DFS. We first have a pass to initialize the states of companies’ controlling states by bootstrapping controlling companies and controlled companies, and also gather company share statistics for each companies. Then we have a second pass to update the global control state where for each company A, if it controls company B (initialized in first pass by calculating if A has over 50% shares of B), then A should also have same number shares for each company C that company B has shares in. This process continues and the global state should converge and reach a fixed state, as for each company, we will do DFS for every other company only once.
voiddfs(int i){ if (i == N) { int sum = 0, cur = 1, sign = 1; for (int i = 2; i <= N; ++i) { char op = s[i - 2]; if (op == ' ') { cur = cur * 10 + i; } else { sum += cur * sign; cur = i; if (op == '+') { sign = 1; } else { sign = -1; } } } sum += cur * sign; if (sum == 0) { res.push_back(s); } return; }