Approach
Depth-first search
For Distinct Gate Paths to Lca, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 80 lines of Python from the credited upstream file distinct-gate-paths-to-lca.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def distinctPaths(self, n, parent, gates, queries):7 """8 :type n: int9 :type parent: List[int]10 :type gates: List[List[int]]11 :type queries: List[List[int]]12 :rtype: int13 """14 MOD = 10**9+715 BB, BR, RB, RR = range(4)16 def ceil_log2(x):17 return (x-1).bit_length()18 19 def mult(x, y):20 return (21 (x[BB]*y[BB]+x[BR]*y[RB])%MOD,22 (x[BB]*y[BR]+x[BR]*y[RR])%MOD,23 (x[RB]*y[BB]+x[RR]*y[RB])%MOD,24 (x[RB]*y[BR]+x[RR]*y[RR])%MOD,25 )26 27 def lca(a, b):28 if depth[a] < depth[b]:29 a, b = b, a30 d = depth[a]-depth[b]31 for k in xrange(len(par)):32 if d&(1<<k):33 a = par[k][a]34 if a == b:35 return a36 for k in reversed(xrange(len(par))):37 if par[k][a] != par[k][b]:38 a, b = par[k][a], par[k][b]39 return par[0][a]40 41 def count(u, card, t):42 if u == l:43 return 144 d = depth[u]-depth[t]45 b, r = 1 if card == 0 else 0, 1 if card == 1 else 046 for k in xrange(len(par)):47 if not d&(1<<k):48 continue49 b, r = (b*cnt[k][u][BB]+r*cnt[k][u][RB])%MOD, (b*cnt[k][u][BR]+r*cnt[k][u][RR])%MOD50 u = par[k][u]51 return (b+r)%MOD52 53 adj = [[] for _ in xrange(n)]54 for u in xrange(n):55 if parent[u] != -1:56 adj[parent[u]].append(u)57 depth = [0]*n58 stk = [0]59 while stk:60 u = stk.pop()61 for v in reversed(adj[u]):62 depth[v] = depth[u]+163 stk.append(v)64 par = [[0]*n for _ in xrange(ceil_log2(n-1)+1)]65 cnt = [[(0,)*4 for _ in xrange(n)] for _ in xrange(ceil_log2(n-1)+1)]66 for u in xrange(n):67 par[0][u] = parent[u]68 cnt[0][u] = (gates[u][1], gates[u][2], gates[u][2], gates[u][0])69 for k in xrange(1, len(par)):70 for u in xrange(n):71 if par[k-1][u] == -1:72 continue73 par[k][u] = par[k-1][par[k-1][u]]74 cnt[k][u] = mult(cnt[k-1][u], cnt[k-1][par[k-1][u]])75 result = 076 for q in queries:77 l = lca(q[0], q[2])78 result ^= (count(q[0], q[1], l)*count(q[2], q[3], l))%MOD79 return result80