question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting + LCA | binary-lifting-lca-by-tavvfikk-yyhg | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | tavvfikk | NORMAL | 2025-02-17T01:27:44.168310+00:00 | 2025-02-17T01:27:44.168310+00:00 | 90 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
const int LOG = 31;
vector<vector<pair<int, int>>> graph;
vector<vector<int>> up;
vector<vector<vector<int>>> cost;
vector<int> depth;
vector<int> merge(vector<int>& a, vector<int>& b) {
vector<int> res = a;
for (int i = 0; i < res.size(); ++i)
res[i] += b[i];
return res;
}
void dfs(int u, int p) {
up[0][u] = p;
for (int j = 1; j < LOG; ++j) {
if (up[j - 1][u] != -1) {
up[j][u] = up[j - 1][up[j - 1][u]];
cost[j][u] = merge(cost[j - 1][u], cost[j - 1][up[j - 1][u]]);
}
}
for (const auto& [v, w] : graph[u]) {
if (v == p)
continue;
vector<int> freq(27, 0);
freq[w] = 1;
depth[v] = depth[u] + 1;
cost[0][v] = freq;
dfs(v, u);
}
}
int kth_ancestor(int u, int k, vector<int>& dist) {
for (int j = 0; j < LOG; ++j) {
if ((k >> j) & 1) {
dist = merge(dist, cost[j][u]);
u = up[j][u];
if (u == -1)
break;
}
}
return u;
}
vector<int> query(int u, int v) {
if (depth[v] > depth[u])
swap(u, v);
vector<int> dist(27, 0);
int k = depth[u] - depth[v];
u = kth_ancestor(u, k, dist);
if (u == v)
return dist;
for (int j = LOG - 1; j >= 0; --j) {
if (up[j][u] != up[j][v]) {
dist = merge(dist, cost[j][u]);
dist = merge(dist, cost[j][v]);
u = up[j][u];
v = up[j][v];
}
}
dist = merge(dist, cost[0][u]);
dist = merge(dist, cost[0][v]);
return dist;
}
vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
graph.resize(n + 1);
up.resize(LOG, vector<int>(n + 1, -1));
cost.resize(LOG, vector<vector<int>>(n + 1, vector<int>(27, 0)));
depth.resize(n + 1);
for (const auto& edge : edges) {
graph[edge[0]].push_back({edge[1], edge[2]});
graph[edge[1]].push_back({edge[0], edge[2]});
}
dfs(0, -1);
vector<int> ans(queries.size());
for (int i = 0; i < queries.size(); ++i) {
int u = queries[i][0], v = queries[i][1];
vector<int> freq = query(u, v);
int total_freq = 0;
int max_freq = 0;
for (const auto& val : freq) {
total_freq += val;
max_freq = max(max_freq, val);
}
ans[i] = total_freq - max_freq;
}
return ans;
}
};
``` | 2 | 0 | ['Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting + Frequency Table + DFS || Well Explained || C++ | binary-lifting-frequency-table-dfs-well-dpiik | Approach\n\n1. Build an adjacency list representation of the tree using the given edges.\n\n2. Calculate the frequency of each character (a to z) in the subtree | EGhost08 | NORMAL | 2023-09-09T22:38:56.152358+00:00 | 2023-09-09T22:38:56.152377+00:00 | 64 | false | # Approach\n\n1. Build an adjacency list representation of the tree using the given edges.\n\n2. Calculate the frequency of each character (a to z) in the subtree rooted at each node using a depth-first search (DFS) approach. This can be done by keeping an array `freq` where `freq[node][i]` stores the frequency of character `i` in the subtree rooted at node `node`.\n\n3. Calculate the distance of each node from the root of the tree using another DFS approach. Create an array `dist` where `dist[node]` represents the distance of node `node` from the root node.\n\n4. Build the binary lifting table `up` to efficiently find the lowest common ancestor (LCA) of two nodes. This is done by using dynamic programming. The `up[node][k]` entry stores the 2^k-th ancestor of node `node`.\n\n5. For each query (u, v), find their LCA (lowest common ancestor) using the `lca` function. Then calculate the length of the path from `u` to `v` as `dist[u] + dist[v] - 2 * dist[lca]`.\n\n6. For each character (a to z), calculate the total number of changes needed for this character along the path from `u` to `v`. This can be done by subtracting the frequencies of the character at the LCA node from the sum of frequencies of the character at nodes `u` and `v`. This gives the number of changes needed for that character on the path from `u` to `v`.\n\n7. Update the minimum cost of changes for each query by iterating through all characters and taking the minimum of all character-specific changes.\n\n8. Return the answers for all queries.\n\n# Time Complexity\n\n- Building the adjacency list takes $$O(n)$$ time.\n\n- Calculating character frequencies and distances using DFS takes $$O(n)$$ time.\n\n- Building the binary lifting table (up) takes $$O(n * log(n))$$ time.\n\n- Processing each query takes $$O(log(n))$$ time to find the LCA and $$O(26)$$ time to calculate character-specific changes.\n\n- Overall, the time complexity of the algorithm is $$O(n * log(n) + q * 26)$$, where `n` is the number of nodes, `q` is the number of queries, and 26 is the number of characters in the alphabet.\n\n# Space Complexity\n\n- The space complexity of the algorithm is primarily determined by the data structures used:\n\n - The `freq` array for character frequencies requires $$O(n * 26)$$ space.\n\n - The `dist` array for distances requires $$O(n)$$ space.\n\n - The `up` array for binary lifting requires $$O(n * log(n))$$ space.\n\n - Additional space is used for variables and temporary data structures.\n\n- Therefore, the overall space complexity of the algorithm is $$O(n * log(n))$$, dominated by the `up` array.\n\n# Code\n```\nclass Solution {\n void dfs(int node,int parent,vector<vector<int>> adj[],int &k,vector<vector<int>> &up,vector<int> &tin,vector<int> &tout,int &timer)\n {\n tin[node] = ++timer;\n up[node][0] = parent;\n for(int i=1;i<=k;i++)\n up[node][i]=up[up[node][i-1]][i-1];\n for(auto v : adj[node])\n {\n if(v[0]!=parent)\n dfs(v[0],node,adj,k,up,tin,tout,timer);\n }\n tout[node]= ++timer;\n }\n bool is_ancestor(int u, int v,vector<int> &tin,vector<int> &tout)\n {\n return (tin[u]<=tin[v] && tout[u]>=tout[v]);\n }\n\n int lca(int u,int v,int &k,vector<vector<int>> &up, vector<int> &tin,vector<int> &tout)\n {\n if (is_ancestor(u, v, tin, tout))\n return u;\n\n if (is_ancestor(v, u, tin, tout))\n return v;\n\n for(int i=k;i>=0;i--)\n {\n if (!is_ancestor(up[u][i], v, tin, tout))\n u=up[u][i];\n }\n return up[u][0];\n }\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<int>> adj[n];\n for(auto x:edges)\n {\n adj[x[0]].push_back({x[1],x[2]});\n adj[x[1]].push_back({x[0],x[2]});\n }\n vector<vector<int>> freq(n,vector<int>(27,0));\n calc_freq(freq,adj,0,-1);\n vector<int> dist(n,0);\n calc_dist(adj,dist,0,-1);\n int timer=0;\n vector<int> tin(n+1,0), tout(n+1,0);\n int k=ceil(log2(n));\n vector<vector<int>> up(n,vector<int>(k+1));\n dfs(0, 0,adj,k,up,tin,tout,timer);\n vector<int> ans;\n for(auto x : queries)\n {\n int res = INT_MAX;\n int u = x[0];\n int v = x[1];\n int lc = lca(u,v,k,up,tin,tout);\n int len = dist[u] + dist[v] - 2*dist[lc];\n for(int i=1;i<=26;i++)\n {\n int noc = freq[u][i] + freq[v][i] - 2*freq[lc][i];\n res = min(res,len - noc);\n }\n ans.push_back(res);\n }\n return ans;\n }\n void calc_freq(vector<vector<int>> &freq,vector<vector<int>> adj[],int u,int parent)\n {\n for(auto v : adj[u])\n {\n if(v[0]==parent)\n continue;\n for(int i = 1;i<=26;i++)\n {\n freq[v[0]][i] += freq[u][i];\n }\n freq[v[0]][v[1]]++;\n calc_freq(freq,adj,v[0],u);\n }\n }\n void calc_dist(vector<vector<int>> adj[], vector<int> &dist, int u,int parent)\n {\n for(auto v : adj[u])\n {\n if(v[0]==parent)\n continue;\n dist[v[0]] = dist[u]+1;\n calc_dist(adj,dist,v[0],u);\n }\n }\n};\n``` | 2 | 0 | ['Array', 'Tree', 'Graph', 'Strongly Connected Component', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Java, Explained in details | java-explained-in-details-by-ahtythefict-qk7p | Intuition\nStep 1: First of all you need to know how binary lifting technique works, and I myself learnt it from here https://www.youtube.com/watch?v=oib-XsjFa- | ahtythefiction | NORMAL | 2023-09-09T17:50:48.145429+00:00 | 2023-09-09T17:50:48.145456+00:00 | 67 | false | # Intuition\n***Step 1***: First of all you need to know how binary lifting technique works, and I myself learnt it from here https://www.youtube.com/watch?v=oib-XsjFa-M\n***Step 2***: We will take node 0 as root always. I could add some more techniques to employ strategy for choosing root, but this also passes and works same asymptotically in all the cases.\n***Step 3***: Calculate graph using edges.\n***Step 4***: Calculate LOG variable based on a video I provided.\n***Step 5***: Variable **up** will be initialized with all -1, because I want to know for sure when I\'m jumping out of bounds when doing binary lifting.\n***Step 6***: After that I launch dfs to calculate **weightCounts** and **depth**. **depth** represents the depth of each node relative to root, which is 0, **weightCounts** represents how many and of which type of weights we visited so far until reaching node, again relative to root. Why is it needed? It looks like a prefix sum variable, so when we need to calculate different sums of the weights we visited so far, we will do it. Long story short after calculating LCA ( Lowest Common Ancestor ), the calculation of which you can know from here https://www.youtube.com/watch?v=dOAxrhAUIhA&t=700s , you will know that you need to add up the weights of two paths (root -> query[0]) and (root -> query[1]) and subtract 2 times (root -> lca) - just draw and you will get it, it\'s simple.\n\n\n# Complexity\n- Time complexity:\nO(nlog(n) + qlog(n))\n\n- Space complexity:\nO(nlog(n))\n\n# Code\n```\nclass Solution {\n private static int[] depth;\n private static int[][] weightCounts;\n private static int[][] up;\n private static int LOG;\n private static final int MAX_WEIGHT = 27;\n\n\n public static int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n List<int[]>[] graph = new List[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n\n for (int[] edge : edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n graph[u].add(new int[]{v, w});\n graph[v].add(new int[]{u, w});\n }\n\n LOG = 0;\n for (int i = 0; (1 << i) <= n; i++) {\n LOG++;\n }\n\n up = new int[n][LOG+1];\n for (int j = 0; j < n; j++) {\n Arrays.fill(up[j], -1);\n }\n depth = new int[n];\n weightCounts = new int[n][MAX_WEIGHT];\n dfs(0, -1, graph);\n\n Queue<int[]> nodes = new LinkedList<>();\n nodes.add(new int[]{0, -1});\n while (!nodes.isEmpty()) {\n int[] meta = nodes.poll();\n int node = meta[0], parent = meta[1];\n up[node][0] = parent;\n if (node != 0) {\n for (int j = 1; j <= LOG; j++) {\n if (up[node][j-1] == -1) {\n break;\n }\n up[node][j] = up[ up[node][j-1] ][j-1];\n }\n }\n for (int[] neigh : graph[node]) {\n if (neigh[0] != parent) {\n nodes.add(new int[]{neigh[0], node});\n }\n }\n }\n\n int[] answer = new int[queries.length];\n\n for (int q = 0; q < queries.length; q++) {\n int[] query = queries[q];\n int u = query[0], v = query[1];\n int lca = lca(u, v);\n int[] uweight = Arrays.copyOf(weightCounts[u], MAX_WEIGHT);\n int[] vweight = Arrays.copyOf(weightCounts[v], MAX_WEIGHT);\n int[] lcaweight = Arrays.copyOf(weightCounts[lca], MAX_WEIGHT);\n int[] result = new int[MAX_WEIGHT];\n for (int i = 0; i < MAX_WEIGHT; i++) {\n result[i] = uweight[i] + vweight[i] - 2 * lcaweight[i];\n }\n answer[q] = Arrays.stream(result).sum() - Arrays.stream(result).max().getAsInt();\n }\n\n return answer;\n }\n\n private static int lca(int a, int b) {\n if (depth[a] < depth[b]) return lca(b, a);\n int k = depth[a] - depth[b];\n for (int j = LOG - 1; j >= 0; j--) {\n if ((k & (1 << j)) > 0) {\n a = up[a][j];\n }\n }\n\n if (a == b) return a;\n\n for (int j = LOG - 1; j >= 0; j--) {\n if (up[a][j] != up[b][j]) {\n a = up[a][j];\n b = up[b][j];\n }\n }\n\n return up[a][0];\n }\n\n private static void dfs(int node, int parent, List<int[]>[] graph) {\n for (int[] neighbourWeight : graph[node]) {\n int neighbour = neighbourWeight[0], w = neighbourWeight[1];\n if (neighbour != parent) {\n depth[neighbour] = depth[node] + 1;\n weightCounts[neighbour] = Arrays.copyOf(weightCounts[node], MAX_WEIGHT);\n weightCounts[neighbour][w]++;\n dfs(neighbour, node, graph);\n }\n }\n }\n}\n``` | 2 | 0 | ['Bit Manipulation', 'Depth-First Search', 'Breadth-First Search', 'Java'] | 2 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Step by Step solution using Binary Lifting and LCA | step-by-step-solution-using-binary-lifti-6ua3 | Intuition\n Describe your first thoughts on how to solve this problem. \nIf we can find frequency of all elements from path u to v then we can calculate number | ujjwal___ | NORMAL | 2023-09-04T16:56:15.146941+00:00 | 2023-09-04T16:56:15.146972+00:00 | 69 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf we can find frequency of all elements from path u to v then we can calculate number of operation such that all the values will be equal \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Calculate frequency of all elements till a node and from root and parent of node using using dfs.\n2. Now we can use binary lifting to calculate higher power of nodes using our precomupted result. **up[i][j]=up[up[i-1][j]][j-1]**\n3. Once we have precomputed all up values then we can find lca of two nodes.\n4. Once we have lca then we can find frequency of each weight from path u to v as **weight[i]=wt[v][i]+wt[u][i]-2*wt[lca][i]** \n \n**In case of doubt in lca and binary lifting you can visit errichto algorithms or kartik arora youtube video**\n\n\n# Complexity\n- Time complexity:**(nlogn + qlogn)**\n nlogn for precomputation of up 2d vector and logn in each query to calculate lca to total qlogn for query processing\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: nlogn\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int up[20][10010];\n vector<vector<pair<int,int>>>adj;\n int depth[10010];\n vector<vector<int>>wt;\n \n void dfs(int node,int par,int w){\n up[0][node]=par;\n \n depth[node]=depth[par]+1;\n \n wt[node]=wt[par];\n wt[node][w]++;\n \n for(auto it:adj[node]) if(it.first!=par) dfs(it.first,node,it.second);\n }\n \n int lca(int u,int v){\n \n if(depth[u]<depth[v]){\n swap(u,v);\n }\n \n int diff=depth[u]-depth[v];\n \n for(int i=19;i>=0;i--){\n if((diff&(1<<i))!=0){\n u=up[i][u];\n }\n }\n \n if(u==v) return u;\n \n for(int i=19;i>=0;i--){\n if(up[i][u]!=up[i][v]){\n u=up[i][u];\n v=up[i][v];\n }\n }\n \n return up[0][u];\n }\n \n vector<int>get_wt(int u,int v){\n \n int lc=lca(u,v);\n \n vector<int>w(27,0);\n \n for(int i=0;i<=26;i++){\n w[i]=wt[u][i]+wt[v][i]-2*wt[lc][i];\n }\n \n return w;\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n adj.clear();\n adj.resize(n+1);\n \n wt.clear();\n wt.resize(n+3);\n \n for(auto &it:wt) it.resize(28,0);\n \n \n for(auto it:edges){\n adj[it[0]].push_back({it[1],it[2]});\n adj[it[1]].push_back({it[0],it[2]});\n }\n \n dfs(0,n,27);\n \n for(int j=1;j<20;j++){\n for(int i=0;i<n;i++){\n if(up[j-1][i]!=n) up[j][i]=up[j-1][up[j-1][i]];\n }\n }\n \n int q=queries.size();\n vector<int>ans;\n \n for(auto it:queries){\n int u=it[0];\n int v=it[1];\n \n vector<int>wt_v=get_wt(u,v);\n \n int temp_ans=0;\n \n \n sort(wt_v.rbegin(),wt_v.rend());\n \n for(int i=1;i<=26;i++) temp_ans+=(wt_v[i]);\n \n ans.push_back(temp_ans);\n }\n \n return ans;\n \n \n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Python3 | Tarjan's offline LCA algorithm | python3-tarjans-offline-lca-algorithm-by-qhvu | Intuition\n Describe your first thoughts on how to solve this problem. \nA classic tree problem using LCA. \n\n# Approach\n Describe your approach to solving th | bssrdf | NORMAL | 2023-09-03T18:20:44.416464+00:00 | 2023-09-03T18:28:14.565873+00:00 | 101 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA classic tree problem using LCA. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPreprocess arrays to get the path length (root to node) and count of unique weights (weights have limited number of values) along the path. \n\nUse Tarjan\'s offline LCA algorithm to get answers to all queries in one DFS sweep.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*26)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n G = [[] for _ in range(n)]\n for u,v,w in edges:\n G[u].append([v,w])\n G[v].append([u,w])\n pathLen = [0]*n \n M = (max(w for _,_,w in edges) if edges else 1) +1\n uniq = [[0]*M for _ in range(n)]\n def dfs(u, par, depth, cnt):\n pathLen[u] = depth\n for i in range(1,M):\n uniq[u][i] = cnt[i]\n for v,w in G[u]:\n if v == par: continue\n newc = cnt[:] \n newc[w] += 1\n dfs(v, u, depth+1, newc)\n c = [0]*M \n dfs(0, -1, 0, c) \n def LCA(queries):\n color = [0] * n\n pa = list(range(n))\n def find(x:int) -> int:\n if x != pa[x]:\n pa[x] = find(pa[x])\n return pa[x]\n qs = [[] for _ in range(n)]\n ans = [-1]*len(queries)\n for i, (s, e) in enumerate(queries):\n qs[s].append((e,i)) # \u8DEF\u5F84\u7AEF\u70B9\u5206\u7EC4\n if s != e:\n qs[e].append((s,i))\n def tarjan(x: int, fa: int) -> None:\n color[x] = 1 # \u9012\u5F52\u4E2D\n for y,_ in G[x]:\n if color[y] == 0: # \u672A\u9012\u5F52\n tarjan(y, x)\n pa[y] = x # \u76F8\u5F53\u4E8E\u628A y \u7684\u5B50\u6811\u8282\u70B9\u5168\u90E8 merge \u5230 x\n for y,i in qs[x]:\n # color[y] == 2 \u610F\u5473\u7740 y \u6240\u5728\u5B50\u6811\u5DF2\u7ECF\u904D\u5386\u5B8C\n # \u4E5F\u5C31\u610F\u5473\u7740 y \u5DF2\u7ECF merge \u5230\u5B83\u548C x \u7684 lca \u4E0A\u4E86\n if y == x or color[y] == 2: # \u4ECE y \u5411\u4E0A\u5230\u8FBE lca \u7136\u540E\u62D0\u5F2F\u5411\u4E0B\u5230\u8FBE x\n lca = find(y)\n ans[i] = (pathLen[x] + pathLen[y] - 2 * pathLen[lca] - \n max(uniq[x][k]+uniq[y][k]-2*uniq[lca][k] for k in range(1,M))) \n \n color[x] = 2 # \u9012\u5F52\u7ED3\u675F\n tarjan(0, -1)\n return ans\n \n return LCA(queries)\n``` | 2 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Brute force dfs but still O(nlogn) | brute-force-dfs-but-still-onlogn-by-leet-uvyh | Just in case that you dont know uniou find/binary lifting for LCA but still want to have O(nlogn) time complexity. we can use brute force dfs to return which | leetcode_dafu | NORMAL | 2023-09-03T04:22:10.889871+00:00 | 2023-09-03T06:16:24.511164+00:00 | 192 | false | Just in case that you dont know uniou find/binary lifting for LCA but still want to have O(nlogn) time complexity. we can use brute force dfs to return which queried nodes we have visited but we have not found their matched query partners. This naive dfs algorithm has the following two problems: \n\n1. too many queried nodes to return!!!! say, we have visited nodes [1,2,6,7,8,9,4,.... ], how can we not directly carry all of them when returning them to the parent node? we can use a dict outside the dfs function and only return the key value. E.g. I can set dp[2]=[1,2,6,7,8,9,4,.... ], then only return the key of 2 to the parent node.\n\n2. how to aviod O(n^2) when merging kids\' queried nodes? we always incoporate the shorter sets into the longest set. In this way, the time complexity is at most O(nlogn). for example, the cur node has three kids, one visits [3,6,7,18,51], one visits [2,9], the other visits [17,26,33], we always merge [2,9] and [17,26,33] into [3,6,7,18,51], rather than the other way around.\n\n\n ct=collections.defaultdict(lambda: [0]*27)\n adj=collections.defaultdict(set)\n val,tot=Counter(),Counter()\n \n for i,j,k in edges:\n adj[i].add(j)\n adj[j].add(i)\n val[i,j]=val[j,i]=k\n\n\n def dfs(cur,prev): \n for nxt in adj[cur]-{prev}:\n ct[nxt]=ct[cur][:]\n ct[nxt][val[nxt,cur]]+=1\n tot[nxt]=tot[cur]+1\n dfs(nxt,cur)\n\n dfs(0,-1)\n \n\n q=collections.defaultdict(set)\n index=collections.defaultdict(list)\n\n for k,(i,j) in enumerate(queries): \n q[i].add(j)\n q[j].add(i)\n index[min(i,j),max(i,j)]+=[k]\n\n dp=collections.defaultdict(set)\n\n res=[0]*len(queries)\n\n def t(cur, prev):\n\n kids=[t(nxt,cur) for nxt in adj[cur]-{prev}]+[cur]\n\n x=kids[0]\n\n dp[cur].add(cur)\n\n for y in kids[1:]:\n if len(dp[y])>len(dp[x]):\n x,y=y,x\n \n\n for z in dp[y]:\n\n removes=set()\n\n for w in q[z]: \n\n if w in dp[x]:\n\n q[w].remove(z)\n removes.add(w)\n\n\n if not q[w]:\n dp[x].remove(w)\n\n ans=float(\'inf\')\n\n \n total=tot[w]+tot[z]-2*tot[cur]\n\n for v in range(1,27):\n\n ans=min(ans,total-(ct[w][v]+ct[z][v]-2*ct[cur][v])) \n\n\n for idx in index[min(z,w),max(z,w)]:\n res[idx]=ans\n\n\n for w in removes:\n q[z].remove(w)\n\n\n if q[z]:\n\n dp[x].add(z)\n return x \n\n t(0, -1)\n \n return res\n | 2 | 0 | ['Python'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | ✅☑[C++] || Tree|| Graph || Best Approach🔥 | c-tree-graph-best-approach-by-marksphili-v9zc | \n\n# Code\n\nclass Solution {\n void dfs(const vector<vector<pair<int, int>>> &con, int x, int p, vector<int> &b, vector<int> &e, vector<vector<int>> &f, in | MarkSPhilip31 | NORMAL | 2023-09-03T04:08:50.287452+00:00 | 2023-09-09T21:42:25.628182+00:00 | 231 | false | \n\n# Code\n```\nclass Solution {\n void dfs(const vector<vector<pair<int, int>>> &con, int x, int p, vector<int> &b, vector<int> &e, vector<vector<int>> &f, int &t, vector<vector<int>> &all, vector<int> &w) {\n all[x] = w;\n f[x][0] = p;\n b[x] = ++t;\n for (const auto& v : con[x]) {\n if (v.first != p) {\n ++w[v.second];\n dfs(con, v.first, x, b, e, f, t, all, w);\n --w[v.second];\n }\n }\n e[x] = t;\n}\n \n// Is x an ancestor of y?\nbool isAncestor(const vector<int> &b, const vector<int> &e, int x, int y) {\n\treturn b[x] <= b[y] && e[x] >= e[y];\n}\n \nint lca(const vector<vector<int>> &f, const vector<int> &b, const vector<int> &e, int x, int y) {\n\tif (isAncestor(b, e, x, y)) {\n\t\treturn x;\n\t}\n\tif (isAncestor(b, e, y, x)) {\n\t\treturn y;\n\t}\n \n\tint r = 0;\n\tfor (int i = 19; i >= 0; --i) {\n\t\tconst int temp = f[x][i];\n\t\tif (isAncestor(b, e, temp, y)) {\n\t\t\tr = temp;\n\t\t} else {\n\t\t\tx = temp;\n\t\t}\n\t}\n\treturn r;\n}\n\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<pair<int, int>>> con(n);\n for (const auto& e : edges) {\n con[e[0]].push_back({e[1], e[2] - 1});\n con[e[1]].push_back({e[0], e[2] - 1});\n }\n vector<vector<int>> all(n), f(n, vector<int>(20));\n\t vector<int> b(n), e(n), w(26);\n\t int t = 0;\n\t dfs(con, 0, -1, b, e, f, t, all, w);\n\t f[0][0] = 0;\n\t for (int i = 1; i < 20; ++i) {\n\t\t for (int j = 0; j < n; ++j) {\n\t\t\t f[j][i] = f[f[j][i - 1]][i - 1];\n\t\t }\n\t }\n vector<int> r;\n for (const auto& q : queries) {\n if (q[0] == q[1]) {\n r.push_back(0);\n continue;\n }\n const int t = lca(f, b, e, q[0], q[1]);\n int sum = 0, m = 0;\n for (int i = 0; i < 26; ++i) {\n const int temp = all[q[0]][i] + all[q[1]][i] - (all[t][i] << 1);\n sum += temp;\n m = max(m, temp);\n }\n r.push_back(sum - m);\n }\n return r;\n }\n};\n``` | 2 | 0 | ['Array', 'Tree', 'Graph', 'Strongly Connected Component', 'C++'] | 1 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C# DFS + LCA | c-dfs-lca-by-enze_zhang-ixoc | Free LCA template\nO(logn) Query\n\n# Code\n\npublic class Solution {\n const int N = (int)1e5 + 1;\n int[] h = new int[N], e = new int[N * 2], ne = new i | enze_zhang | NORMAL | 2023-09-03T04:08:28.852818+00:00 | 2023-09-03T10:55:00.301418+00:00 | 52 | false | Free LCA template\nO(logn) Query\n\n# Code\n```\npublic class Solution {\n const int N = (int)1e5 + 1;\n int[] h = new int[N], e = new int[N * 2], ne = new int[N * 2], w = new int[N];\n int[,] f = new int[N, 31], fa = new int[N, 31];\n int[] depth = new int[N];\n int idx = 0;\n \n public void Build(int u, int v, int c){\n e[idx] = v; ne[idx] = h[u]; w[idx] = c; h[u] = idx++;\n e[idx] = u; ne[idx] = h[v]; w[idx] = c; h[v] = idx++;\n }\n \n public void Bfs(int rt){\n Array.Fill(depth, int.MaxValue);\n depth[0] = 0;\n depth[rt] = 1;\n Queue<int> que = new();\n\n que.Enqueue(rt);\n while(que.Count > 0){\n int t = que.Dequeue();\n for(int i = h[t]; i != -1; i = ne[i]){\n int j = e[i];\n if(depth[j] > depth[t] + 1){ \n depth[j] = depth[t] + 1; \n que.Enqueue(j);\n fa[j, 0] = t; \n for(int k = 1; k <= 15; k++){\n fa[j, k] = fa[fa[j, k - 1], k - 1];\n }\n }\n }\n }\n }\n \n public void Dfs(int u, int fa){\n for(int i = h[u]; i != -1; i = ne[i]){\n int v = e[i];\n if(v == fa) continue;\n f[v, w[i]] += 1; \n for(int j = 1; j <= 26; j++){\n f[v, j] += f[u, j];\n }\n Dfs(v, u);\n }\n }\n\n public int Lca(int a, int b){\n if(depth[a] < depth[b]){\n int tmp = b;\n b = a;\n a = tmp;\n }\n for(int k = 15; k >=0; k--){\n if(depth[fa[a, k]] >= depth[b])\n a = fa[a, k];\n }\n if(a == b) return a;\n\n for(int k = 15; k >= 0; k--){\n if(fa[a, k] != fa[b, k]){\n a = fa[a, k];\n b = fa[b, k];\n }\n }\n return fa[a, 0];\n }\n \n public int[] MinOperationsQueries(int n, int[][] edges, int[][] queries) {\n Array.Fill(h, -1);\n for(int i = 0; i < edges.Length; i++){\n int a = edges[i][0], b = edges[i][1], c = edges[i][2];\n Build(a, b, c);\n }\n \n Bfs(0);\n Dfs(0, 0);\n List<int> ysy = new();\n for(int i = 0; i < queries.Length; i++){\n int u = queries[i][0], v = queries[i][1];\n int anc = Lca(u, v);\n int max = 0;\n for(int j = 1; j <= 26; j++){\n max = Math.Max(f[u, j] + f[v, j] - f[anc, j] * 2, max);\n }\n ysy.Add(depth[u] + depth[v] - 2 * depth[anc] - max);\n }\n return ysy.ToArray();\n }\n}\n``` | 2 | 0 | ['C#'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA-Binary Lifting | lca-binary-lifting-by-twasim-lqyy | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | twasim | NORMAL | 2024-10-14T00:31:46.712870+00:00 | 2024-10-14T00:31:46.712891+00:00 | 67 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n vector<int> in, out;\n int p[15][10005], tt;\n int fre[27][10005];\n \n void dfs(int node, int par, vector<pair<int, int>> adj[], int l = 0) {\n in[node] = tt++;\n p[0][node] = par; // Store the parent of the current node\n \n for (int i = 1; i < 15; i++) {\n p[i][node] = p[i - 1][p[i - 1][node]]; // Binary lifting for ancestors\n }\n \n for (auto x : adj[node]) {\n if (x.first == par) continue; // Skip the parent\n \n for (int i = 1; i <= 26; i++) {\n fre[i][x.first] = fre[i][node]; // Propagate frequencies\n }\n fre[x.second][x.first]++; // Increment the frequency of the weight of the edge\n dfs(x.first, node, adj); // Recursively call DFS on the child\n }\n out[node] = tt++;\n }\n \n bool check(int a, int b) {\n return (in[a] <= in[b] && out[a] >= out[b]); // a is an ancestor of b\n }\n \n int lca(int a, int b) {\n if (check(a, b)) return a;\n if (check(b, a)) return b;\n for (int i = 14; i >= 0; i--) {\n if (!check(p[i][a], b)) {\n a = p[i][a]; // Lift node `a` upwards\n }\n }\n return p[0][a]; // The final parent will be the LCA\n }\n\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n memset(fre, 0, sizeof(fre));\n in.resize(n);\n out.resize(n);\n tt = 0;\n \n vector<pair<int, int>> adj[n];\n for (auto x : edges) {\n adj[x[0]].push_back({x[1], x[2]});\n adj[x[1]].push_back({x[0], x[2]});\n }\n \n dfs(0, 0, adj); // Start DFS from node 0\n \n vector<int> ans;\n for (auto x : queries) {\n int a = x[0];\n int b = x[1];\n int la = lca(a, b); // Find the LCA of nodes a and b\n \n int temp_ans = 0;\n int total = 0;\n \n for (int i = 1; i <= 26; i++) {\n total += fre[i][a] + fre[i][b] - 2 * fre[i][la]; // Frequency contribution\n temp_ans = max(temp_ans, fre[i][a] + fre[i][b] - 2 * fre[i][la]); // Maximum frequency in path\n }\n ans.push_back(total - temp_ans); // Minimum operations to equalize\n }\n return ans;\n }\n};\n\n``` | 1 | 0 | ['Tree', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Solution Using Binary Lifting | solution-using-binary-lifting-by-yashu76-75el | \n# Code\n\nclass Solution {\nprivate:\n vector<int> vis;\n vector<vector<int>> up; // Binary lifting table\n int l;\n vector<int> tin;\n vector | yashu761 | NORMAL | 2024-08-15T15:51:33.222477+00:00 | 2024-08-15T15:51:33.222517+00:00 | 93 | false | \n# Code\n```\nclass Solution {\nprivate:\n vector<int> vis;\n vector<vector<int>> up; // Binary lifting table\n int l;\n vector<int> tin;\n vector<int> tout;\n int timer=0;\n vector<vector<pair<int, int>>> graph;\n \n void dfs3(int node, int parent,vector<vector<int>>& w) {\n vis[node] = 1;\n tin[node] = ++timer;\n up[node][0] = parent;\n \n \n for (int i = 1; i <= l; ++i) up[node][i] = up[up[node][i - 1]][i - 1];\n \n for (auto it : graph[node]) {\n if (it.first == parent) continue;\n if (!vis[it.first]) {\n for (int i = 1; i <= 26; i++) w[it.first][i] += w[node][i];\n \n w[it.first][it.second]++;\n dfs3(it.first, node, w);\n }\n }\n tout[node]=++timer;\n }\n bool is_ancestor(int u, int v){\n return tin[u] <= tin[v] && tout[u] >= tout[v];\n } \n int lca(int u, int v){\n\n if (is_ancestor(u, v))\n return u;\n if (is_ancestor(v, u))\n return v;\n for (int i = l; i >=0; --i) {\n if (!is_ancestor(up[u][i], v))\n u = up[u][i];\n }\n return up[u][0];\n }\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<int> ans;\n vector<vector<int>> w(n+1, vector<int>(27, 0));\n graph.resize(n);\n\n for (auto it : edges) {\n graph[it[0]].emplace_back(it[1], it[2]);\n graph[it[1]].emplace_back(it[0], it[2]);\n }\n\n vis.resize(n, 0);\n l = ceil(log2(n+1));\n up.assign(n, vector<int>(l + 1));\n tin.resize(n);\n tout.resize(n);\n\n dfs3(0, 0, w);\n for (auto it : queries) {\n int s = it[0];\n int e = it[1];\n\n int lcaa = lca(s, e);\n vector<int> vec(27, 0);\n for (int i = 1; i <= 26; i++) {\n vec[i] = w[s][i] + w[e][i] - 2 * w[lcaa][i];\n }\n int maxFreq = 0;\n int sum=0;\n for (int i = 1; i <= 26; i++) {\n sum+=vec[i];\n maxFreq = max(maxFreq, vec[i]);\n }\n ans.push_back(sum - maxFreq);\n }\n\n return ans;\n }\n};\n\n``` | 1 | 0 | ['Graph', 'Strongly Connected Component', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting and LCA | binary-lifting-and-lca-by-praneeth_nellu-qsjz | \nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n """\n Pre-requisit | praneeth_nellut1 | NORMAL | 2023-11-08T10:49:53.590633+00:00 | 2023-11-08T10:49:53.590661+00:00 | 16 | false | ```\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n """\n Pre-requisite for seeing this solution is binary lifting and LCA.\n """\n graph = [[] for i in range(n)]\n maxN = int(log(n, 2))\n lca = [[-1 for i in range(maxN + 1)] for j in range(n)]\n level = [0 for i in range(n)]\n freq = [[0 for i in range(27)] for j in range(n)]\n res = []\n\n # construct a graph with given edges\n for src, dest, weight in edges:\n graph[src].append((dest, weight))\n graph[dest].append((src, weight))\n\n """ \n find the level and first parents of each node and also calculate \n maintain a frequency array of each edge weight\n """\n def dfs(node, par):\n lca[node][0] = par\n level[node] = level[par] + 1\n for nei, w in graph[node]:\n if nei == par:\n continue\n freq[nei] = freq[node][:]\n freq[nei][w] += 1\n dfs(nei, node)\n\n\n dfs(0, 0)\n\n # populate parents of every node at a distance of 2 powers\n for j in range(1, maxN + 1):\n for i in range(1, n):\n lca[i][j] = lca[lca[i][j - 1]][j - 1]\n\n # finding LCA using lca array and binary lifting concept\n def findLCA(a, b):\n if level[a] > level[b]:\n a, b = b, a\n d = level[b] - level[a]\n while d:\n i = int(log(d, 2))\n b = lca[b][i]\n d -= (1 << i)\n if a == b:\n return a\n for i in range(maxN, -1, -1):\n if lca[a][i] != -1 and lca[a][i] != lca[b][i]:\n a = lca[a][i]\n b = lca[b][i]\n return lca[a][0]\n\n # calculating res for each query\n for u, v in queries:\n par = findLCA(u, v)\n temp = [freq[u][w] + freq[v][w] - 2 * freq[par][w] for w in range(27)]\n res.append(sum(temp) - max(temp))\n return res\n\n \n``` | 1 | 0 | ['Array', 'Tree', 'Graph', 'Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Maaza aa Gaya - TLE -> MLE -> Accepted | maaza-aa-gaya-tle-mle-accepted-by-onnhyd-4mrd | Intuition\nTry to apply normal LCA using hashmap to find maximum frequent weight and total weight count.\n\n\n# Approach\n Hint\n (1/4)\n Root the tree | onnhyd | NORMAL | 2023-09-05T18:32:51.863868+00:00 | 2023-09-05T18:34:04.971400+00:00 | 25 | false | # Intuition\nTry to apply normal LCA using hashmap to find maximum frequent weight and total weight count.\n\n\n# Approach\n Hint\n (1/4)\n Root the tree at any node.\n\n\n Hint\n (2/4)\n Define a 2D array freq[node][weight] which saves the frequency of each edge weight on the path from the root to each node.\n\n Hint\n (3/4)\n The frequency of edge weight w on the path from a to b is equal to freq[a][w] + freq[b][w] - freq[lca(a,b)][w] * 2, where lca(a,b) is the lowest common ancestor of a and b in the tree.\n\n Hint\n (4/4)\n lca(a,b) can be calculated using binary lifting algorithm or Tarjan algorithm.\n\n<!-- # Complexity\n- Time complexity:\n\n\n- Space complexity: -->\n\n# Code (Time Limit Exceeded) :\n```\nclass Solution {\npublic:\n void AssignParentAndHeight(map<int, pair<int, int>>&parent, \n map<int, vector<pair<int, int>>>&graph, int nn, int h, int par,\n map<int, int>&height)\n {\n for(auto &ch : graph[nn])\n {\n int ch0 = ch.first;\n int w = ch.second;\n if(ch0 == par)continue;\n parent[ch0] = {nn, w};\n AssignParentAndHeight(parent, graph, ch0, h + 1, nn, height);\n }\n height[nn] = h; \n }\n int CalculateCost(int l, int r, map<int, pair<int, int>>& parent, map<int, int>& height, \n map<int, vector<pair<int, int>>>& graph)\n {\n map<int, int>mp;\n // cout<<l<<" "<<r<<endl;\n // cout<<"height "<<height[l]<<" "<<height[r]<<endl;\n while(height[l] < height[r])\n {\n auto p = parent[r];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n r = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n while(height[l] > height[r])\n {\n auto p = parent[l];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n l = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n while(l != r)\n {\n auto p = parent[l];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n l = par;\n mp[w]++;\n p = parent[r];\n p1 = p.second;\n p0 = p.first;\n w = p1;\n par = p0;\n r = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n int tot = 0;\n int mx = 0;\n for(auto &m : mp)\n {\n int f = m.second;\n if(f > mx)mx = f;\n tot += f;\n }\n // cout<<tot<<" "<<mx<<endl;\n return tot - mx;\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n map<int, pair<int, int>>parent;\n map<int, vector<pair<int, int>>>graph;\n map<int, int>height;\n for(auto &edge : edges)\n {\n int a = edge[0], b = edge[1], w = edge[2];\n graph[a].push_back({b, w});\n graph[b].push_back({a, w});\n }\n int nn = 0;\n int h = 1;\n int par = -1;\n // cout<<"debug 1"<<endl;\n AssignParentAndHeight(parent, graph, nn, h, par, height); \n // cout<<"debug 2"<<endl;\n vector<int>ans;\n for(auto &query : queries)\n {\n int l = query[0], r = query[1];\n // cout<<"debug 2"<<endl;\n int q = CalculateCost(l, r, parent, height, graph);\n ans.push_back(q);\n } \n return ans; \n }\n};\n```\n# Code(Memory Limit Exceeded)\n```\nclass Solution {\npublic:\n vector<vector<int>>DP;\n void AssignParentAndHeight(vector<pair<int, int>>&parent, \n vector<vector<pair<int, int>>>&graph, int nn, int h, int par,\n vector<int>&height)\n {\n for(auto &ch : graph[nn])\n {\n int ch0 = ch.first;\n int w = ch.second;\n if(ch0 == par)continue;\n parent[ch0] = {nn, w};\n AssignParentAndHeight(parent, graph, ch0, h + 1, nn, height);\n }\n height[nn] = h; \n }\n int CalculateCost(int l, int r, vector<pair<int, int>>& parent, vector<int>& height, \n vector<vector<pair<int, int>>>& graph)\n {\n // cout<<l<<" "<<r<<endl;\n int L = l, R = r;\n // cout<<DP[l][r]<<endl;\n if(DP[l][r] != -1)return DP[l][r];\n map<int, int>mp;\n \n // cout<<"height "<<height[l]<<" "<<height[r]<<endl;\n while(height[l] < height[r])\n {\n auto p = parent[r];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n r = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n while(height[l] > height[r])\n {\n auto p = parent[l];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n l = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n while(l != r)\n {\n auto p = parent[l];\n int p1 = p.second;\n int p0 = p.first;\n int w = p1;\n int par = p0;\n l = par;\n mp[w]++;\n p = parent[r];\n p1 = p.second;\n p0 = p.first;\n w = p1;\n par = p0;\n r = par;\n mp[w]++;\n }\n // cout<<l<<" "<<r<<endl;\n int tot = 0;\n int mx = 0;\n for(auto &m : mp)\n {\n int f = m.second;\n if(f > mx)mx = f;\n tot += f;\n }\n // cout<<tot<<" "<<mx<<endl;\n return DP[L][R] = tot - mx;\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n DP.resize(n, vector<int>(n, -1));\n DP[0][0] = -1;\n vector<pair<int, int>>parent(n);\n vector<vector<pair<int, int>>>graph(n);\n vector<int>height(n);\n for(auto &edge : edges)\n {\n int a = edge[0], b = edge[1], w = edge[2];\n graph[a].push_back({b, w});\n graph[b].push_back({a, w});\n }\n int nn = 0;\n int h = 1;\n int par = -1;\n // cout<<"debug 1"<<endl;\n AssignParentAndHeight(parent, graph, nn, h, par, height); \n // cout<<"debug 2"<<endl;\n vector<int>ans;\n for(auto &query : queries)\n {\n int l = query[0], r = query[1];\n // cout<<"debug 2"<<endl;\n int q = CalculateCost(l, r, parent, height, graph);\n ans.push_back(q);\n } \n return ans; \n }\n};\n```\n# Code (Accepted)\n```\nclass Solution {\npublic:\n\nint FindCostToChange(int l, int r, vector<vector<pair<int, int>>>&graph, vector<vector<int>>& parent,\nvector<int>& level, vector<vector<int>>&root_to_node)\n{\n int L = l, R = r;\n // cout<<"L "<<L<<" R "<<R<<endl;\n if(level[l] > level[r])\n {\n // cout<<"r is a high position"<<endl;\n int diff = level[l] - level[r];\n //push l on top\n for(int i = 0; i < 32; i++)\n {\n if(((1<<i)&diff) != 0)\n {\n l = parent[l][i];\n }\n }\n }\n if(level[l] < level[r])\n {\n // cout<<"l is a high position"<<endl;\n int diff = level[r] - level[l];\n // cout<<"diff : "<<diff<<endl;\n //push r on top\n for(int i = 0; i < 32; i++)\n {\n if(((1<<i)&diff) != 0)\n {\n // cout<<"i "<<i<<endl;\n r = parent[r][i];\n // cout<<"new r "<<r<<endl;\n }\n }\n }\n // cout<<"l "<<l<<" r "<<r<<endl;\n // cout<<"level "<<level[l]<<" "<<level[r]<<endl;\n while(l != r)\n {\n l = parent[l][0];\n r = parent[r][0];\n }\n int tot = 0, mx = 0;\n // cout<<L<<" "<<R<<" "<<l<<endl;\n for(int i = 0; i < 27; i++)\n {\n \n int we = root_to_node[L][i] + root_to_node[R][i] - 2 * (root_to_node[l][i]);\n // if(i == 1)\n // {\n // cout<<"L "<<L<<" i "<<i<<" root to L "<<root_to_node[L][i]<<endl;\n // cout<<"R "<<L<<" i "<<i<< " root to R "<<root_to_node[R][i]<<endl;\n // cout<<root_to_node[L][i]<<endl;\n // cout<<root_to_node[R][i]<<endl;\n // cout<<root_to_node[l][i]<<endl;\n // cout<<"we "<<we<<endl;\n // }\n // if(we > 0)cout<<i<<endl;\n if(we > mx)mx = we;\n tot += we;\n }\n // cout<<"lca "<<l<<endl;\n // cout<<"root to lca "<<root_to_node[l][2]<<endl;\n // cout<<"root to 3 "<<root_to_node[L][2]<<endl;\n // cout<<"root to 6 "<<root_to_node[R][2]<<endl;\n // cout<<"LCA "<<l<<endl;\n // cout<<"L "<<L<<" R "<<R<<" tot "<<tot<<" mx "<<mx<<endl;\n // cout<<"L "<<L<<" R "<<R<<endl;\n // cout<<"tot "<<tot<<" mx "<<mx<<endl;\n return tot - mx;\n}\n\nvoid AssignParentAndLevel(vector<vector<pair<int, int>>>&graph,\n vector<vector<int>>& parent, \n vector<int>& level, \n vector<int>&weight, \n vector<vector<int>>&root_to_node,\n int nn, int curr, int par = -2)\n {\n level[nn] = curr;\n root_to_node[nn] = weight;\n // cout<<"nn "<<nn<<" ";\n // for(auto &wt : weight)cout<<wt<<" "; cout<<endl;\n for(auto &chp : graph[nn])\n {\n int ch = chp.first;\n int w = chp.second;\n if(ch == par)continue;\n // parent[ch][1] = nn;\n int pp = nn;\n int lift = 0;\n int add = 0;\n while(pp >= 0)\n {\n parent[ch][lift] = pp;\n pp = parent[pp][add];\n add++;\n lift++;\n }\n weight[w]++;\n AssignParentAndLevel(graph, parent, level, weight, root_to_node, ch, curr + 1, nn);\n weight[w]--;\n }\n\n\n }\nvector<int> minOperationsQueries(int n, \n vector<vector<int>>& edges, \n vector<vector<int>>& queries) {\n vector<vector<pair<int, int>>>graph(n);\n for(auto &e : edges)\n {\n int u = e[0], v = e[1], w = e[2];\n graph[u].push_back({v, w});\n graph[v].push_back({u, w});\n }\n // cout<<"graph formed"<<endl;\n vector<vector<int>>parent(n, vector<int>(32, -1));\n vector<int>level(n);\n vector<vector<int>>root_to_node(n, vector<int>(27, 0));\n vector<int>weight(27, 0);\n int nn = 0;\n int curr = 1;\n AssignParentAndLevel(graph, parent, level, weight, root_to_node, nn, curr);\n // for(auto &it : parent)\n // {\n // for(auto &i : it)cout<<i<<" "; cout<<endl;\n // }\n // cout<<"parent and level assigned"<<endl;\n \n // for(auto &rtn : root_to_node)\n // {\n // for(auto &r : rtn)cout<<r<<" ";cout<<endl;\n // }\n vector<int>ans;\n for(auto &q :queries)\n {\n int l = q[0], r = q[1];\n int a = FindCostToChange(l, r, graph, parent, level, root_to_node);\n ans.push_back(a);\n } \n return ans;\n }\n};\n``` | 1 | 1 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Simple C++ solution using LCA and DFS | simple-c-solution-using-lca-and-dfs-by-g-aqji | \n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nKey observation is that weights | Grim77 | NORMAL | 2023-09-04T23:36:39.605122+00:00 | 2023-09-04T23:37:28.161241+00:00 | 22 | false | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nKey observation is that weights are between 1 and 26. First, we will precompute a vector containing the weights in the path from root to each node using simple DFS. Then we will use Binary Lifting to find LCA of the nodes given in each query. Using these two computations, we will get our answer.\n\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nstatic const int lg=15;\nstatic const int N=1e4+10;\nint up[N][lg];\nint lvl[N];\nvoid binlift(int src,int par,vector<pair<int,int>>tree[]){\n up[src][0]=par;\n for (int i = 1; i < lg; i++)\n {\n if (up[src][i-1]!=-1)\n {\n up[src][i]=up[up[src][i-1]][i-1];\n }\n else\n {\n up[src][i]=-1;\n } \n }\n for (auto val : tree[src])\n {\n if (val.first!=par)\n {\n binlift(val.first,src,tree);\n }\n \n } \n}\nint ans_query(int node,int jump){\n if(node==-1||jump==0){\n return node;\n }\n for (int i = lg-1; i >= 0; i--)\n {\n if (jump>=(1<<i))\n {\n return ans_query(up[node][i],jump-(1<<i));\n }\n \n }\n return -1;\n \n}\nvoid dfs(int src,int par,int lev,vector<pair<int,int>>tree[],vector<int>vx,vector<int>vec[]){\n lvl[src]=lev;\n vec[src]=vx;\n for (auto val : tree[src])\n {\n if (val.first!=par)\n {\n vx[val.second]++;\n dfs(val.first,src,lev+1,tree,vx,vec);\n vx[val.second]--;\n }\n \n }\n \n}\nint LCA(int u,int v){\n if(lvl[u]<lvl[v]){\n swap(u,v);\n }\n u=ans_query(u,lvl[u]-lvl[v]);\n if(u==v){\n return u;\n }\n for (int i = lg-1; i >=0; i--)\n {\n if (up[u][i]!=up[v][i])\n {\n u=up[u][i];\n v=up[v][i];\n }\n \n }\n return ans_query(u,1);\n \n}\n\nvector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n\n vector<pair<int,int>>g[n+1];\n for(auto val:edges){\n g[val[0]].push_back({val[1],val[2]});\n g[val[1]].push_back({val[0],val[2]});\n }\n vector<int>vec[n+1];\n for(int i=0;i<=n;i++){\n for(int ii=0;ii<lg;ii++){\n up[i][ii]=-1;\n lvl[i]=0;\n }\n }\n vector<int>vx(27,0);\n binlift(0,-1,g);\n dfs(0,-1,1,g,vx,vec);\n vector<int>aa;\n\n for(auto val:queries){\n int com = LCA(val[0],val[1]);\n int sum=0;\n int ma=0;\n for(int i=1;i<=26;i++){\n int tot = vec[val[0]][i]+vec[val[1]][i]-2*vec[com][i];\n sum+=tot;\n ma=max(ma,tot);\n\n\n }\n aa.push_back(sum-ma);\n \n }\n\n return aa;\n\n \n }\n};\n``` | 1 | 1 | ['Binary Search', 'Tree', 'Depth-First Search', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Lowest Common Ancestor || Explanation and Solution [C++] | lowest-common-ancestor-explanation-and-s-q0hh | *To do this, you must first know Binary Lifting.\n\n Choose any 1 node as the root.\n Find the difference between two nodes u and v.\n From the difference then | doantrunghuy | NORMAL | 2023-09-04T13:01:42.549327+00:00 | 2023-09-04T14:08:24.324658+00:00 | 133 | false | ****To do this, you must first know Binary Lifting.****\n\n* Choose any 1 node as the root.\n* Find the difference between two nodes u and v.\n* From the difference then lift up. When they are the same height u and v we will use Binary Lifting to find the nearest ancestor by finding the node closest to the ancestor and then we only need to jump 1 step to find the nearest ancestor.\n* Then this will be the way to find the smallest change for all equal weights. Realize the value is only in the range (1 <= wi <= 26). Then we can store the occurrences through the array "cls[n][26]". In the article, I gave wi -1. This is to check a subtree to see how many times that value appears.\n* Then we will subtract the length from u -> v to the value that occurs most in u -> v. From there will be the minimum number of steps to change the value.\n\n****Vote if you think it\'s good****\n\n****Here is my C++ code you can refer to****\n```\nusing pii = pair<int, int>;\nconst int MW = 26;\n\nclass Solution {\nprivate:\n vector<vector<pii>> adj;\n vector<vector<int>> par, clr;\n vector<int> depth;\n int n, m;\n \npublic:\n void dfs(int u, int p, int c) {\n par[u][0] = p;\n depth[u] = c;\n for (const auto &[v, w] : adj[u]) {\n if (v == p) {\n continue;\n }\n for (int i = 0; i < MW; ++i) {\n clr[v][i] = clr[u][i] + (i == w);\n }\n dfs(v, u, c + 1);\n }\n }\n \n int get_node_lca(int u, int v) {\n if (depth[u] < depth[v]) {\n swap(u, v);\n }\n \n int diff = depth[u] - depth[v];\n \n for (int i = m; i >= 0; --i) {\n if ((diff >> i) & 1) {\n u = par[u][i];\n }\n }\n \n if (u == v) {\n return u;\n }\n \n for (int i = m; i >= 0; --i) {\n if (par[u][i] != par[v][i]) {\n u = par[u][i];\n v = par[v][i];\n }\n }\n \n return par[u][0];\n }\n \n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n this->n = n;\n adj.resize(n);\n \n for (vector<int> edge : edges) {\n int u = edge[0];\n int v = edge[1];\n int w = edge[2];\n w--;\n adj[u].push_back({v, w});\n adj[v].push_back({u, w});\n }\n \n depth.resize(n);\n m = ceil(log2(n));\n par.resize(n, vector<int>(m + 1, -1));\n clr.resize(n, vector<int>(MW));\n dfs(0, -1, 1);\n \n for (int j = 1; j <= m; ++j) {\n for (int i = 0; i < n; ++i) {\n if (par[i][j - 1] != -1) {\n par[i][j] = par[par[i][j - 1]][j - 1];\n }\n }\n }\n \n int sz_q = queries.size();\n \n vector<int> ans(sz_q, n);\n \n for (int j = 0; j < sz_q; ++j) {\n int u = queries[j][0];\n int v = queries[j][1];\n int node_lca = get_node_lca(u, v);\n int len = depth[u] + depth[v] - 2*depth[node_lca];\n for (int i = 0; i < MW; ++i) {\n int try_num = (clr[u][i] + clr[v][i] - 2*clr[node_lca][i]);\n ans[j] = min(ans[j], len - try_num);\n }\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Tree', 'Depth-First Search', 'C'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ | Binary Lifting | LCA | 🚀🚀 Simple🔥 Clean Code | Easy to Understand✅ | c-binary-lifting-lca-simple-clean-code-e-3ji4 | the approach is to find the lowest common ancestor of node a and b and then to find the maximum same type of w between a and b if we know the max same between a | yeah_boi123 | NORMAL | 2023-09-04T09:02:24.278535+00:00 | 2023-09-04T09:02:24.278560+00:00 | 57 | false | the approach is to find the lowest common ancestor of node a and b and then to find the maximum same type of w between a and b if we know the max same between a and b then we can change remaining between them so to do this we need to first find the lca of a and b so what are the requirements for lca \n1.parent array - stores the parent of each node\n2.lvl array- stores the level of each node from root\n3.dp array for storing the kth parent \n4.jump function to make particular no of jumps\n5.getlca function to find lca using these\n\nnow once we have the lca now we can have track of no diffrent w till lca and we also have track of diffrent w till a and b subtracting them we can get total in the range a to b now we can replace all those whose occurence is less than maxi to make it same \n\n# Code\n```\nclass Solution {\npublic:\n int jump(int node,int k,vector<vector<int>> &dp){\n\n int curr=node;\n for(int i=20; i>=0; i--){\n if(curr!=-1 && (k&(1<<i))){\n curr=dp[curr][i];\n }\n }\n return curr;\n }\n void findp(int node,int p,vector<int> adj[],vector<int> &par){\n par[node]=p;\n for(int child:adj[node]){\n if(child!=p){\n findp(child,node,adj,par);\n }\n }\n }\n\n void findlvl(int node,int par,int l,vector<int> adj[],vector<int> &lvl){\n lvl[node]=l;\n for(int child:adj[node]){\n if(child!=par){\n findlvl(child,node,l+1,adj,lvl);\n }\n }\n }\n int getlca(int a,int b,vector<vector<int>> &dp,vector<int> &lvl){\n int la=lvl[a];\n int lb=lvl[b];\n if(lvl[a]>lvl[b]){\n swap(a,b);\n swap(la,lb);\n }\n int diff=lb-la;\n b=jump(b,diff,dp);\n if(a==b){\n return a;\n }\n for(int i=20; i>=0; i--){\n if(dp[a][i]!=dp[b][i]){\n a=dp[a][i];\n b=dp[b][i];\n }\n }\n return jump(a,1,dp);\n }\n\n void dfs(int node,int par,int val,vector<pair<int,int>> adj[],vector<vector<int>> &kitna){\n if(par!=-1){\n for(int i=0; i<=26; i++){\n kitna[node][i]=kitna[par][i];\n if(i==val){\n kitna[node][i]++;\n }\n }\n } \n \n for(auto it:adj[node]){\n int child=it.first;\n int v=it.second;\n if(child!=par){\n dfs(child,node,v,adj,kitna);\n }\n }\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& q) {\n vector<int> adj[n];\n vector<pair<int,int>> adj1[n];\n for(int i=0; i<edges.size(); i++){\n int x=edges[i][0];\n int y=edges[i][1];\n int w=edges[i][2];\n adj[x].push_back(y);\n adj[y].push_back(x);\n adj1[x].push_back({y,w});\n adj1[y].push_back({x,w});\n }\n vector<vector<int>> dp(n,vector<int> (21,-1));\n vector<int> par(n,-1);\n findp(0,-1,adj,par);\n vector<int> lvl(n,0);\n findlvl(0,-1,0,adj,lvl);\n for(int i=0; i<n; i++){\n dp[i][0]=par[i];\n }\n for(int j=1; j<=20; j++){\n for(int i=0; i<n; i++){\n if(dp[i][j-1]!=-1){\n dp[i][j]=dp[dp[i][j-1]][j-1];\n }\n }\n }\n vector<vector<int>> kitna(n,vector<int> (27,0));\n vector<int> ans;\n dfs(0,-1,-1,adj1,kitna);\n for(int i=0;i<q.size(); i++){\n int x=q[i][0];\n int y=q[i][1];\n int lca=getlca(x,y,dp,lvl);\n int dis=(lvl[x]+lvl[y]-2*lvl[lca]);\n int maxi=0;\n for(int i=0; i<=26; i++){\n int c=kitna[lca][i];\n int l=kitna[x][i];\n int r=kitna[y][i];\n int tot=(r+l-2*c);\n maxi=max(maxi,tot);\n }\n ans.push_back(dis-maxi);\n // return dis-maxi;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Tree', 'C++'] | 1 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary search, Lowest common ancestor | binary-search-lowest-common-ancestor-by-hexo8 | Intuition\n Describe your first thoughts on how to solve this problem. \nRoot the tree. For each query (A, B), find the path from A to the root and that from B | LordAlgorithms | NORMAL | 2023-09-03T10:06:27.994109+00:00 | 2023-09-03T10:09:31.060474+00:00 | 144 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRoot the tree. For each query (A, B), find the path from A to the root and that from B to the root. Get rid of redudant common nodes and keep only the latest one. The combination of the two paths would be the path from A to B. Try to optimize each part of the implements. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1) Pre-process the edges. Convert the array into dictionary to facilitate the following\n investigations. Time complexity: O(N). Space complexity: O(N).\n\n 2) Root the tree and store the children and the parent of each node. O(N)\n Evaluate the frequencies of the weights for the path from each node to the root. O(N * W)\n Time complexity: O(N * W). Space complexity: O(N * W)\n\n 3) For each query, which has two end nodes, say A and B\n 3.1. get the path from A to the root and that from B to the root. Use cache to reduce the\n time complexity to O(Q), which the space complexity is up to O(N^2).\n 3.2. find the lowest common ancestor of the two paths. Use binary search to reduce the time\n complexity to O(Q logN). Space complexity is O(1).\n 3.3. evaluate the weight frequencies. Sum the frequencies of A and B, and subtract those of\n LCA twice. The number of weights is no more than 26. Time complexity: O(Q W). Space complexity: O(W).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N * W + Q logN + Q * W)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N * W + N^2)\n# Code\n```\nclass Solution:\n\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n tree = defaultdict(set)\n weights = defaultdict(int)\n for a, b, w in edges:\n tree[a].add(b)\n tree[b].add(a)\n weights[(a, b)] = weights[(b, a)] = w\n mx = 0\n if weights:\n mx = max(weights.values())\n\n fws = [[0] * (mx+1) for _ in range(n)]\n children = defaultdict(set) # root the tree. essentially, we convert the data structure of\n parent = defaultdict(int) # the tree into that of \'children\' and \'parent\'.\n dq = deque([0])\n while dq:\n p = dq.popleft()\n for c in tree[p]:\n if c != parent[p]: # it is also ok to record the seen nodes in a set\n children[p].add(c)\n parent[c] = p\n dq.append(c)\n w0 = weights[(c, p)]\n for w in range(1, mx+1):\n fws[c][w] = fws[p][w] + (w == w0)\n del tree, weights\n \n @lru_cache(None)\n def get_path(x: int) -> [int]:\n """ get the path from the root to the node x """\n if x == 0:\n return [0]\n return get_path(parent[x]) + [x]\n\n def lca(path1, path2) -> int:\n """ find the least common ancestor. Use binary search to speed it up """\n lo = 0\n hi = min(len(path1), len(path2))-1\n while lo <= hi:\n m = (lo+hi) // 2\n if path1[m] == path2[m]:\n lo = m + 1\n else:\n hi = m - 1\n return hi\n\n ans = []\n for a, b in queries:\n if a == b:\n ans.append(0)\n else:\n pa, pb = get_path(a), get_path(b)\n i = lca(pa, pb)\n joint = pa[i]\n ws = fws[a].copy()\n for j, w in enumerate(fws[b]):\n ws[j] += w\n for j, w in enumerate(fws[joint]):\n ws[j] -= w * 2\n ans.append(sum(ws) - max(ws))\n return ans\n``` | 1 | 0 | ['Binary Search', 'Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | DFS + LCA using Sparse Table | dfs-lca-using-sparse-table-by-roboto7o32-jdsu | Code\n\nclass LCA {\npublic:\n vector<int> depth, euler, first;\n vector<vector<int>> st;\n int n, m, k;\n\n LCA() {}\n\n // Initialize the class | roboto7o32oo3 | NORMAL | 2023-09-03T04:01:11.313589+00:00 | 2023-09-03T04:03:18.833411+00:00 | 72 | false | # Code\n```\nclass LCA {\npublic:\n vector<int> depth, euler, first;\n vector<vector<int>> st;\n int n, m, k;\n\n LCA() {}\n\n // Initialize the class with the adjacency list of the tree and the root node.\n void init(vector<vector<int>>& AList, int root=0) {\n n = AList.size();\n depth.resize(n);\n first.resize(n);\n euler.clear();\n\n depth[root] = 0;\n dfs(root, -1, AList);\n\n build();\n }\n\n // Performs euler tour and computes the depth of each node.\n void dfs(int u, int parent, vector<vector<int>>& AList) {\n first[u] = euler.size();\n euler.push_back(u);\n\n for(int v : AList[u]) {\n if(v == parent) continue;\n depth[v] = 1 + depth[u];\n dfs(v, u, AList);\n euler.push_back(u);\n }\n }\n\n // Builds the sparse table.\n void build() {\n m = euler.size();\n k = __builtin_clz(1) - __builtin_clz(m);\n\n st.assign(k+1, vector<int>(m));\n\n copy(euler.begin(), euler.end(), st[0].begin());\n\n for(int i = 1; i <= k; i++) {\n for(int j = 0; j + (1<<i) <= m; j++) {\n int left = st[i-1][j];\n int right = st[i-1][j + (1<<(i-1))];\n\n st[i][j] = (depth[left] < depth[right] ? left : right);\n }\n }\n }\n\n // Range minimum query for the node with the least depth between the range l and r.\n int query(int l, int r) {\n int len = r-l+1;\n int i = __builtin_clz(1) - __builtin_clz(len);\n\n int left = st[i][l];\n int right = st[i][r - (1<<i) + 1];\n\n return depth[left] < depth[right] ? left : right;\n }\n\n // Lowest common ancestor of two nodes u and v.\n int lca(int u, int v) {\n assert(u>=0 and u<n and v>=0 and v<n);\n int left = first[u], right = first[v];\n if(left > right) swap(left, right);\n return query(left, right);\n }\n\n // Distance between two nodes u and v.\n int distance(int u, int v) {\n assert(u>=0 and u<n and v>=0 and v<n);\n return depth[u] + depth[v] - 2*depth[lca(u, v)];\n }\n} lca;\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<pair<int,int>>> AList(n);\n vector<vector<int>> AList_(n);\n \n for(vector<int>& edge : edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n \n AList[u].push_back({v, w});\n AList[v].push_back({u, w});\n AList_[u].push_back(v);\n AList_[v].push_back(u);\n }\n \n vector<vector<int>> vec(n, vector<int>(26, 0));\n int root = 0;\n \n function<void(int,int)> dfs = [&](int u, int parent) {\n for(auto& [v, w] : AList[u]) {\n if(v == parent) continue;\n \n vec[v] = vec[u];\n vec[v][w-1]++;\n \n dfs(v, u);\n }\n };\n \n dfs(root, -1);\n \n vector<int> result(queries.size());\n \n lca.init(AList_);\n \n for(int i=0; i<queries.size(); i++) {\n int u = queries[i][0], v = queries[i][1];\n \n int l = lca.lca(u, v);\n \n int sum = 0, ma = 0;\n \n for(int j=0; j<26; j++) {\n int val = vec[u][j] + vec[v][j] - 2*vec[l][j];\n sum += val;\n ma = max(ma, val);\n }\n \n result[i] = sum - ma;\n }\n \n return result;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | just another implementation | just-another-implementation-by-harshmang-kahx | the idea was to populate the LCA [1] and use recursion (function f, in the impl) to store, for each node, the number of weights encountered when one reaches the | harshmangalamv | NORMAL | 2025-03-26T18:19:45.831122+00:00 | 2025-03-26T18:19:45.831122+00:00 | 3 | false | the idea was to populate the LCA [[1]](https://cp-algorithms.com/graph/lca_binary_lifting.html) and use recursion (function f, in the impl) to store, for each node, the number of weights encountered when one reaches there from the assumed (and fixed) root. 0th node is root in all cases.
# Code
```cpp []
class Solution {
void f(int node, int par, vector<vector<pair<int, int>>>&g, vector<vector<int>>& weights){
for(auto x: g[node]){
auto ch = x.first;
auto w = x.second;
if(ch != par){
weights[ch] = weights[node];
weights[ch][w]++;
f(ch, node, g, weigths);
}
}
}
void dfs(int a, int b, int& timer, vector<vector<int>>&up, vector<vector<pair<int, int>>>&g, vector<int>&tin, vector<int>&tout){
up[a][0] = b;
tin[a] = ++timer;
for(int i=1; i<=16; i++){
up[a][i] = up[up[a][i-1]][i-1];
}
for(auto x: g[a]){
int ch = x.first;
if(ch != b){
dfs(ch, a, timer, up, g, tin, tout);
}
}
tout[a] = ++timer;
}
bool is_ancestor(int a, int b, vector<int>&tin, vector<int>&tout){
return ((tin[a]<=tin[b]) && (tout[a]>=tout[b]));
}
int findLCA(int a, int b, vector<vector<int>>& up, vector<int>&tin, vector<int>&tout){
if(is_ancestor(a, b, tin, tout)){return a;}
if(is_ancestor(b, a, tin, tout)) {return b;}
for(int i=16; i>=0; i--){
if(!is_ancestor(up[a][i], b, tin, tout)) a = up[a][i];
}
return up[a][0];
}
public:
vector<int> minOperationsQueries(int n, vector<vector<int>>& e, vector<vector<int>>& q) {
// always rooting at zero, no matter what
vector<vector<pair<int, int>>>g(n);
vector<vector<int>>w(n, vector<int>(27));
vector<vector<int>>up(n+2, vector<int>(17));
vector<int>tin(n+2);
vector<int>tout(n+2);
int timer = 0;
//make the graph (yes it is tree by definition in our PS)
for(auto x: e){
g[x[0]].push_back({x[1], x[2]});
g[x[1]].push_back({x[0], x[2]});
}
// make the table ready
dfs(0, 0, timer, up, g, tin, tout);
// recursion, stores the
f(0, 0, g, w);
vector<int>ans;
for(int i=0; i<q.size(); i++){
int a = q[i][0], b = q[i][1];
int lca = findLCA(a, b, up, tin, tout);
vector<int>v = w[a];
for(int i=0; i<w[b].size(); i++) v[i] += w[b][i];
for(int i=0; i<w[lca].size(); i++) v[i] -= 2*w[lca][i];
int total = 0;
int mx = 0;
for(auto x: v) if(x) {
mx = max(mx, x);
total+=x;
}
ans.push_back(total-mx);
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | EASY C++ SOLUTION || USING BINARY LIFTING || LCA | easy-c-solution-using-binary-lifting-lca-rtqh | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | suraj_kumar_rock | NORMAL | 2025-03-20T00:31:56.865817+00:00 | 2025-03-20T00:31:56.865817+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
vector<vector<pair<int, int>>>adj;
vector<int>level;
vector<vector<int>>curr_node;
vector<vector<int>>freq_node;
void binary_lifting(int node, int par)
{
level[node] = level[par]+1;
curr_node[node][0] = par;
for(int i=1; i<16; i++)
{
curr_node[node][i] = curr_node[curr_node[node][i-1]][i-1];
}
for(auto &x: adj[node])
{
if(x.first == par)
continue;
freq_node[x.first] = freq_node[node];
freq_node[x.first][x.second]++;
binary_lifting(x.first, node);
}
}
int find_lca(int u, int v)
{
if(level[u] < level[v])
swap(u, v);
int diff = level[u] - level[v];
for(int i=0; i <= 15; i++)
{
if((1 << i) & diff)
{
u = curr_node[u][i];
}
}
if(u == v)
return u;
for(int i=15; i>=0; i--)
{
if(curr_node[u][i] != curr_node[v][i])
{
u = curr_node[u][i];
v = curr_node[v][i];
}
}
return curr_node[u][0];
}
public:
vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
adj.clear();
level.clear();
curr_node.clear();
freq_node.clear();
adj.resize(n+5, vector<pair<int, int>>(16, {0, 0}));
curr_node.resize(n+5, vector<int>(16, 0));
level.resize(n+5, 0);
freq_node.resize(n+5, vector<int>(28, 0));
for(auto &x: edges)
{
adj[x[0] + 1].push_back({x[1] + 1, x[2]});
adj[x[1] + 1].push_back({x[0] + 1, x[2]});
}
binary_lifting(1, 0);
vector<int>answer;
for(auto &x: queries)
{
int u = x[0] + 1;
int v = x[1] + 1;
int curr_lca = find_lca(u, v);
vector<int>freq(28, 0);
for(int i=1; i<28; i++)
{
freq[i] = freq_node[u][i] + freq_node[v][i] - 2*freq_node[curr_lca][i];
}
int sum = 0, maxi = 0;
for(auto &x: freq)
{
maxi = max(maxi, x);
sum += x;
}
answer.push_back(sum - maxi);
}
return answer;
}
};
``` | 0 | 0 | ['Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting | binary-lifting-by-maxorgus-86mj | Code\npython3 []\nclass Solution:\n step = 15\n @cache\n def getKthAncestor(self, node: int, k: int) -> int:\n step = self.step\n while k | MaxOrgus | NORMAL | 2024-12-02T06:17:10.213889+00:00 | 2024-12-02T06:17:10.213939+00:00 | 4 | false | # Code\n```python3 []\nclass Solution:\n step = 15\n @cache\n def getKthAncestor(self, node: int, k: int) -> int:\n step = self.step\n while k > 0 and node>-1:\n if k >= 1<<step:\n node = self.jump[step].get(node,-1)\n k -= 1<<step\n else:\n step -= 1\n return node\n \n def getLCA(self,u,v):\n if self.depth[u]>self.depth[v]: u,v = v,u\n diff = self.depth[v]-self.depth[u]\n v = self.getKthAncestor(v,diff)\n if u == v: return u\n for i in range(self.step,-1,-1):\n if u in self.jump[i]:\n uu = self.jump[i][u]\n else:\n uu = -1\n if v in self.jump[i]:\n vv = self.jump[i][v]\n else:\n vv = -1\n if uu == vv:continue\n u = uu\n v = vv\n return self.parents[u]\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n graph = {i:set([]) for i in range(n)}\n for u,v,w in edges:\n graph[u].add((v,w))\n graph[v].add((u,w))\n self.freq = {i:{} for i in range(n)}\n self.currfreq = {} \n self.parents = [-1]*n\n self.depth = [0]*n\n def dfs(node,parent,d):\n self.parents[node] = parent\n self.depth[node] = d\n self.freq[node] = {f:self.currfreq[f] for f in self.currfreq}\n for child,w in graph[node]:\n if child == parent:continue\n if w not in self.currfreq:self.currfreq[w] = 0\n self.currfreq[w] += 1\n dfs(child,node,d+1)\n self.currfreq[w] -= 1\n if self.currfreq[w] == 0:\n del self.currfreq[w]\n dfs(0,-1,0)\n self.P = dict(enumerate(self.parents))\n jump = [self.P]\n for x in range(self.step):\n B = {}\n for i in self.P:\n if self.P[i] in self.P:\n B[i] = self.P[self.P[i]]\n jump.append(B)\n self.P = B\n self.jump = jump\n res = []\n for a,b in queries:\n lca = self.getLCA(a,b)\n alllen = self.depth[a] + self.depth[b] - 2*self.depth[lca]\n Ws = self.freq[a].keys() | self.freq[b].keys()\n currres = alllen\n for w in Ws:\n fwa = 0\n fwb = 0 \n fwl = 0\n if w in self.freq[a]: fwa = self.freq[a][w]\n if w in self.freq[b]: fwb = self.freq[b][w]\n if w in self.freq[lca]: fwl = self.freq[lca][w]\n currres = min(alllen - (fwa+fwb-2*fwl),currres)\n res.append(currres)\n\n return res\n\n\n\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Java | Beats 100% | LCA Using Binary Lifting | Clean Code | java-beats-100-lca-using-binary-lifting-7qwip | Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n\n Ad | mishram19 | NORMAL | 2024-10-10T06:48:19.135281+00:00 | 2024-10-10T06:48:19.135333+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n class Edge {\n int nbd, weight;\n public Edge(int nbd, int weight) {\n this.nbd = nbd;\n this.weight = weight;\n }\n }\n List<List<Edge>> edgeList;\n int[] depth, parent, minOperationReqd;\n int[][] edgeWeightFreq, ancestorDP;\n int maxPower, m;\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n m = queries.length;\n init(n);\n createGraph(n, edges);\n dfs(0, -1, new int[27]);\n //System.out.print("depth -> ");for (int i=0;i<n;i++) {System.out.print("i="+i+","+depth[i] + " :: "); }System.out.println();\n generateBinaryLiftingDPArrayToComputeLCA(n);\n for (int i=0; i<m; i++) {\n int u = queries[i][0], v = queries[i][1];\n int lca = findLCA(u, v);\n //System.out.println("u="+u+", v="+v+", lca="+lca);\n minOperationReqd[i] = computeMinOperations(u, v, lca);\n }\n return minOperationReqd;\n }\n\n void generateBinaryLiftingDPArrayToComputeLCA(int n) {\n for (int j=1; j<maxPower; j++) {\n for (int i=0; i<n; i++) {\n int midAncestor = ancestorDP[i][j-1];\n ancestorDP[i][j] = midAncestor == -1 ? -1 : ancestorDP[ midAncestor ][j-1];\n }\n }\n }\n\n int findLCA(int u, int v) {\n //System.out.println("findLCA -> u="+u+", v="+v);\n if (depth[u] < depth[v]) return findLCA(v, u);\n int node = u;\n for (int i=maxPower-1; i>=0; i--) {\n int stepCnt = (1 << i);\n if ( (depth[node] - stepCnt ) >= depth[v]) {\n node = ancestorDP[node][i];\n }\n } \n //System.out.println("mid -> u="+node+", v="+v);\n if (node == v) return node;\n for (int i=maxPower-1; i>=0; i--) {\n if (ancestorDP[node][i] != ancestorDP[v][i]) {\n node = ancestorDP[node][i];\n v = ancestorDP[v][i];\n }\n } \n //System.out.println("u="+node+", v="+v);\n return ancestorDP[node][0];\n\n }\n\n int computeMinOperations(int u, int v, int lca) {\n int maxNum = 0, totalSum = 0;\n for (int i=1; i<=26; i++) {\n int curPathFreq = edgeWeightFreq[u][i] + edgeWeightFreq[v][i] - 2 * edgeWeightFreq[lca][i];\n totalSum += curPathFreq;\n maxNum = Math.max(maxNum, curPathFreq);\n }\n return totalSum - maxNum;\n }\n\n void dfs(int node, int parent, int[] freq) {\n //System.out.println("dfs= > "+node+", parent="+parent);\n ancestorDP[node][0] = parent;\n for (Edge edge : edgeList.get(node)) {\n int nbd = edge.nbd;\n if (nbd == parent) continue;\n int edgeWeight = edge.weight;\n freq[ edgeWeight ]++;\n depth[nbd] = depth[node] + 1;\n for (int i=1; i<=26; i++) {\n edgeWeightFreq[nbd][i] = freq[i];\n }\n dfs(nbd, node, freq);\n freq[ edgeWeight ]--;\n }\n }\n\n void createGraph(int n, int[][] edges) {\n for (int i=0; i<n; i++) {\n edgeList.add(new ArrayList<>());\n }\n for (int i=0; i<edges.length; i++) {\n edgeList.get(edges[i][0]).add(new Edge(edges[i][1], edges[i][2]));\n edgeList.get(edges[i][1]).add(new Edge(edges[i][0], edges[i][2]));\n }\n }\n\n void init(int n) {\n depth = new int[n];\n parent = new int[n];\n maxPower = (int) (Math.log(n) / Math.log(2)) + 1;\n ancestorDP = new int[n][maxPower];\n minOperationReqd = new int[m];\n edgeWeightFreq = new int[n][27];\n edgeList = new ArrayList<>();\n }\n\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ Modular and well commented code: Root at center + Binary lifting | c-modular-and-well-commented-code-root-a-e0ud | Intuition\n Describe your first thoughts on how to solve this problem. \nRooting the tree at the center makes the code a little longer, but ensures that the pat | pradyumnaym | NORMAL | 2024-10-05T12:32:23.668240+00:00 | 2024-10-05T12:32:23.668273+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRooting the tree at the center makes the code a little longer, but ensures that the path lengths of the trees are as balanced as possible. Since each query is processed in logarithmic time, this is not really essential, but is a good practice.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nWe simply root the tree at the center of the tree (found by the 2-DFS method for center finding). Next, we compute the binary lifting table. Along with the binary lifting table, we also store a frequency distribution of the edge weights each jump comes across. This is then used to find the number of non majority weights, which is the answer.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(NlogN + QlogN)$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(NlogN)$\n\n# Code\n```cpp []\nbitset<10000> visited;\nint path[10000];\nint parent[10000];\nint depth[10000];\nint weight[10000];\n\nstruct freqDist {\n int f[26] = {0};\n\n int getMax() {\n return *max_element(f, f+26);\n }\n\n int getNumberOfNonMax() {\n return accumulate(f, f + 26, 0) - getMax();\n }\n\n freqDist operator+(const freqDist& d2) {\n freqDist dd;\n for (int i = 0; i < 26; i++) {\n dd.f[i] = this->f[i] + d2.f[i];\n }\n return dd;\n }\n\n freqDist& operator=(const freqDist& d2) {\n memcpy(this->f, d2.f, 26 * sizeof(int));\n return *this;\n }\n};\n\nint l[10000][15];\nfreqDist wd[10000][15];\n\nclass Solution {\n\n private:\n vector<vector<pair<int, int>>> adjlist;\n\n // Code to find one extremity of the diameter - used to find the center.\n // we can also use the same code for the final center of the diameter.\n int farthestNode, farthestDistance;\n int pathLen, centerNode;\n\n void dfsFarthest(int node) {\n if(visited[node]) return;\n\n visited[node] = 1;\n path[pathLen++] = node;\n\n if (pathLen > farthestDistance + 1) {\n farthestNode = node;\n farthestDistance = pathLen - 1;\n centerNode = path[pathLen / 2];\n }\n\n for (auto &[i, w]: adjlist[node]) dfsFarthest(i);\n\n visited[node] = 0;\n pathLen--;\n }\n\n // Code to root the tree at the center\n // this builds the parent, depth, and the weight arrays.\n void rootTree(int node, int par, int w, int d) {\n if (visited[node]) return;\n\n parent[node] = par;\n depth[node] = d;\n weight[node] = w;\n\n // define the first level of binary lifting here\n l[node][0] = par;\n if (node != par) wd[node][0].f[w] += 1;\n \n visited[node] = 1;\n for (auto &[i, w1]: adjlist[node]) {\n rootTree(i, node, w1, d + 1);\n }\n\n visited[node] = 0;\n }\n\n // Build the actual lifting table in O(nlogn) time. use the depth array\n // to make sure we stay in bounds.\n void dfsLift(int node) {\n\n if (visited[node]) return;\n\n visited[node] = 1;\n for (int i = 1; i < 15; i++) {\n // need to check if this lift is possible to do.\n // if possible, we also use the freq distribution\n // of the two smaller jumps to construct \n // freq distribution for the full jump.\n if (depth[node] >= (1<<i)) {\n int par = l[node][i-1];\n l[node][i] = l[par][i-1];\n wd[node][i] = wd[node][i-1] + wd[par][i-1];\n }\n }\n\n for (auto &[i, w]: adjlist[node]) dfsLift(i);\n visited[node] = 0;\n }\n\n // use the lift table to compute the kth ancestor\n // and also the weight distribution along this path.\n pair<freqDist, int> kthAncestor(int node, int k) {\n freqDist d;\n if(!k) return {d, node};\n\n for (int i = 0; i < 15 and node != centerNode; i++) {\n if (k & (1 << i)) {\n d = d + wd[node][i];\n node = l[node][i];\n // cout << "lifted at i = " << i << \' \' << wd[node][i].f[0] << endl;\n }\n }\n\n // for (int i = 0; i < 26; i++) cout << d.f[i] << " ";\n // cout << endl << node << endl << endl;\n return {d, node};\n }\n\npublic:\n vector<int> minOperationsQueries(\n int n, \n vector<vector<int>>& edges, \n vector<vector<int>>& queries\n ) {\n \n memset(wd, 0, sizeof(freqDist) * 10000 * 15);\n memset(l, 0, sizeof(int) * 10000 * 15);\n\n // Init the adjlist\n adjlist = vector<vector<pair<int ,int>>>(n, vector<pair<int, int>>());\n for (auto &x : edges) {\n int u = x[0], v = x[1], w = x[2];\n adjlist[u].push_back({v, w - 1});\n adjlist[v].push_back({u, w - 1});\n }\n\n // start from a random node, and find the farthest node\n visited.reset();\n farthestDistance = -1;\n dfsFarthest(0);\n\n // now find the farthest node from this node to find the diameter\n // and the center of the tree.\n farthestDistance = -1;\n dfsFarthest(farthestNode);\n\n // root the tree at the center\n visited.reset();\n rootTree(centerNode, centerNode, 0, 0);\n \n // cout << "Rooted the tree at the center " << centerNode << endl;\n // for (int i = 0; i < n; i++) {\n // cout << parent[i] << " " << depth[i] << " " << weight[i] << endl;\n // }\n\n // build Lift table\n dfsLift(centerNode);\n\n vector<int> ans(queries.size(), 0);\n\n // Now we can simply process the queries\n // Eacy query takes O(Logn) time.\n\n for(int i = 0; i < queries.size(); i++) {\n\n int a = queries[i][0], b = queries[i][1];\n\n // if it is the same node, no need to do any work.\n if (a == b) continue;\n \n // keep the lower node in \'a\'\n if (depth[a] < depth[b]) swap(a, b);\n\n // lift the lower node, so we have the same depth for both nodes\n // also, get the freq distribution of the edges\n // that we need to cross to go from \'a\' to the same depth as \'b\'.\n auto [d, aa] = kthAncestor(a, depth[a] - depth[b]);\n a = aa;\n\n // cout << a << " " << b << " updated" << endl;\n\n int dep = depth[b];\n \n // now simply keep moving both a and b upwards, and \n // update the frequency distribution after each jump taken.\n\n if (a != b) {\n //keep going up\n for (int i = 14; i >=0 ; i--) {\n // if we can take a jump, take it.\n if ((1 << i) <= dep and l[a][i] != l[b][i]) {\n d = d + wd[a][i] + wd[b][i];\n a = l[a][i];\n b = l[b][i];\n dep -= 1<<i;\n }\n }\n\n // finally, both a and b need to move 1 edge up to meet\n // so we take a path length of 1, which is the direct parent.\n d = d + wd[a][0] + wd[b][0];\n }\n ans[i] = d.getNumberOfNonMax();\n }\n\n return ans;\n }\n};\n\nauto init = [](){\n ios::sync_with_stdio(0);\n cin.tie(0);\n return 0;\n}();\n\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Solution using Binary Lifting | solution-using-binary-lifting-by-tanish_-8ghm | Intuition\n Describe your first thoughts on how to solve this problem. \nSolve CSES Binary Lifting Question first(Tree Distances 2)\n# Approach\n Describe your | tanish_chugh | NORMAL | 2024-10-03T10:51:44.001456+00:00 | 2024-10-03T10:51:44.001494+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSolve CSES Binary Lifting Question first(Tree Distances 2)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> edgeFreq;\n vector<vector<pair<int, int>>> adj;\n vector<int> dist;\n vector<vector<int>> dp;\n\n void dfs(int node, int prev, vector<int> weights){\n for(int i=1; i<=26; i++){\n edgeFreq[node][i] += weights[i];\n }\n for(auto it:adj[node]){\n int adjNode = it.first;\n int wt = it.second;\n if(adjNode != prev){\n weights[wt]++;\n dfs(adjNode, node, weights);\n weights[wt]--;\n }\n }\n }\n\n void DFS(int node, int prev){\n for(auto it:adj[node]){\n if(it.first != prev){\n dist[it.first] = 1 + dist[node];\n DFS(it.first, node);\n }\n }\n }\n\n void binaryLifting(int node, int prev){\n dp[node][0] = prev;\n for(int i=1; i<21; i++){\n if(dp[node][i-1] != -1){\n dp[node][i] = dp[dp[node][i-1]][i-1];\n }\n }\n\n for(auto it:adj[node]){\n if(it.first != prev){\n binaryLifting(it.first, node);\n }\n }\n }\n\n // Function to find lca of two elements\n int LCA(int u, int v, int n){\n // Bringing u and v to the same level\n if(dist[v] < dist[u]){\n swap(u, v);\n }\n int k = dist[v] - dist[u];\n int index = 0;\n while(k){\n if(k&1){\n if(v != -1){\n v = dp[v][index];\n }\n }\n\n k = k/2;\n index++;\n }\n\n if(v == u){\n return v;\n }\n // Now since u and v are on same level, we will find their lca(You can see cses for this concept)\n for(int i=20; i>=0; i--){\n if(dp[u][i] != dp[v][i]){\n u = dp[u][i];\n v = dp[v][i];\n }\n }\n\n return dp[u][0];\n }\n\n // .... ... .. .\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n int m = queries.size();\n adj.resize(n);\n edgeFreq.resize(n, vector<int> (27, 0));\n\n for(auto it:edges){\n int u = it[0];\n int v = it[1];\n int wt = it[2];\n\n adj[u].push_back({v, wt});\n adj[v].push_back({u, wt});\n }\n\n // Dfs to store the freq of all the edges from root(Considering 0 as root)\n vector<int> weights(27, 0);\n dfs(0, -1, weights);\n\n // Storing the distance and dp vector for finding lca using binary lifting\n dist.resize(n, 0);\n dp.resize(n, vector<int> (21, -1));\n DFS(0, -1);\n // Using binary lifting to store the kth ancestor\n binaryLifting(0, -1);\n\n vector<int> result;\n for(auto it:queries){\n int u = it[0];\n int v = it[1];\n // Finding LCA Using binary lifting\n int lca = LCA(u, v, n);\n\n vector<int> m1 = edgeFreq[u];\n vector<int> m2 = edgeFreq[v];\n vector<int> m3 = edgeFreq[lca];\n\n // Removing the frequency of edges present in path root node 0(assumed) to lca from frequency of edges present in path root node 0(assumed) to u and v respectively;\n // Adding the frequency of edges present in path root node 0 to u to frequency of edges present in path 0 to v\n for(int i=1; i<=26; i++){\n m1[i] -= m3[i];\n m2[i] -= m3[i];\n m1[i] += m2[i];\n }\n\n int maxi = 0;\n int totalEdges = 0;\n for(auto it:m1){\n maxi = max(maxi, it);\n totalEdges+=it;\n }\n \n result.push_back(totalEdges - maxi);\n }\n\n return result;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Bit Manipulation', 'Tree', 'Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Solution Using Binary Lifting!! | solution-using-binary-lifting-by-kndudhu-folm | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kndudhushyanthan | NORMAL | 2024-09-08T13:05:13.664907+00:00 | 2024-09-08T13:05:13.664935+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n map<int, vector<int>> mp;\n vector<vector<int>> sparse;\n vector<int> level;\n\n void dfs_lca(int node, int par, vector<vector<pair<int, int>>>& adj) {\n sparse[node][0] = par; \n for (int j = 1; j < 21; j++) {\n sparse[node][j] = sparse[sparse[node][j - 1]][j - 1];\n }\n for (auto x : adj[node]) {\n if (x.first != par) {\n level[x.first] = level[node] + 1;\n dfs_lca(x.first, node, adj);\n }\n }\n }\n\n int moveUp(int y, int val) {\n for (int i = 20; i >= 0; i--) { \n if (val & (1 << i)) {\n y = sparse[y][i];\n }\n }\n return y;\n }\n\n int LCA(int x, int y) {\n if (level[x] > level[y]) swap(x, y);\n y = moveUp(y, level[y] - level[x]);\n if(x==y) return x;\n for (int i = 20; i >= 0; i--) { \n if (sparse[x][i] != sparse[y][i]) {\n x = sparse[x][i];\n y = sparse[y][i];\n }\n }\n return sparse[x][0];\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& qur) {\n if (n == 1) {\n vector<int> ans;\n for (const auto& query : qur) {\n ans.push_back(0); \n }\n return ans;\n }\n queue<pair<int, vector<int>>> q;\n vector<int> p(27, 0);\n q.push({1, p}); \n sparse.resize(n + 1, vector<int>(21));\n level.resize(n + 1, 0); \n\n vector<vector<pair<int, int>>> adj(n + 1);\n for (int i = 0; i < edges.size(); i++) {\n int u = edges[i][0];\n int v = edges[i][1];\n int w = edges[i][2];\n adj[u].push_back({v, w});\n adj[v].push_back({u, w});\n }\n\n dfs_lca(1, 1, adj); \n mp[1] = p;\n vector<int> vis(n + 1, 0);\n vis[1] = 1;\n\n while (!q.empty()) {\n auto it = q.front();\n q.pop();\n int node = it.first;\n vector<int> curr = it.second;\n mp[node] = curr;\n for (auto x : adj[node]) {\n vector<int> vec = curr;\n int v = x.first;\n int w = x.second;\n if (!vis[v]) {\n vec[w]++;\n q.push({v, vec});\n vis[v] = 1; \n vec[w]--; \n }\n }\n }\n\n vector<int> ans;\n for (int i = 0; i < qur.size(); i++) {\n int u = qur[i][0];\n int v = qur[i][1];\n int lca = LCA(u, v);\n vector<int> curr(27, 0);\n int freq = 0;\n for (int i = 1; i <= 26; i++) { \n curr[i] = mp[u][i] + mp[v][i] - 2 * mp[lca][i];\n }\n ans.push_back(accumulate(curr.begin(), curr.end(), 0) - *max_element(curr.begin(), curr.end()));\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Easy Solution using Template for finding LCA | easy-solution-using-template-for-finding-gvyk | used template to find lowest common ancestor in O(1);\n\nclass LCA {\n int n, logN;\n vector<int> euler, depth, firstOccurrence;\n vector<v | kvivekcodes | NORMAL | 2024-09-02T07:47:54.692069+00:00 | 2024-09-02T07:47:54.692106+00:00 | 4 | false | used template to find lowest common ancestor in O(1);\n```\nclass LCA {\n int n, logN;\n vector<int> euler, depth, firstOccurrence;\n vector<vector<int>> sparseTable;\n\n void dfs(int node, int parent, int d, const vector<vector<int>>& adj) {\n firstOccurrence[node] = euler.size();\n euler.push_back(node);\n depth.push_back(d);\n \n for (int neighbor : adj[node]) {\n if (neighbor != parent) {\n dfs(neighbor, node, d + 1, adj);\n euler.push_back(node);\n depth.push_back(d);\n }\n }\n }\n\n void buildSparseTable() {\n int m = euler.size();\n logN = log2(m) + 1;\n sparseTable.assign(m, vector<int>(logN));\n\n // Initialize the sparse table with the depth indices\n for (int i = 0; i < m; i++) {\n sparseTable[i][0] = i;\n }\n\n // Build the Sparse Table\n for (int j = 1; (1 << j) <= m; j++) {\n for (int i = 0; i + (1 << j) <= m; i++) {\n int left = sparseTable[i][j-1];\n int right = sparseTable[i + (1 << (j-1))][j-1];\n sparseTable[i][j] = (depth[left] < depth[right]) ? left : right;\n }\n }\n }\n\n int querySparseTable(int l, int r) {\n int length = r - l + 1;\n int j = log2(length);\n int left = sparseTable[l][j];\n int right = sparseTable[r - (1 << j) + 1][j];\n return (depth[left] < depth[right]) ? left : right;\n }\n\n public:\n LCA(const vector<vector<int>>& adj, int root) {\n n = adj.size();\n euler.reserve(2 * n - 1);\n depth.reserve(2 * n - 1);\n firstOccurrence.assign(n, -1);\n\n // Perform Euler Tour\n dfs(root, -1, 0, adj);\n\n // Build the Sparse Table based on the depth array\n buildSparseTable();\n }\n\n int getLCA(int u, int v) {\n int left = firstOccurrence[u];\n int right = firstOccurrence[v];\n if (left > right) swap(left, right);\n int idx = querySparseTable(left, right);\n return euler[idx];\n }\n };\n```\n\n# Code\n```cpp []\nclass Solution {\n\n // used template to find lowest common ancestor in O(1);\n class LCA {\n int n, logN;\n vector<int> euler, depth, firstOccurrence;\n vector<vector<int>> sparseTable;\n\n void dfs(int node, int parent, int d, const vector<vector<int>>& adj) {\n firstOccurrence[node] = euler.size();\n euler.push_back(node);\n depth.push_back(d);\n \n for (int neighbor : adj[node]) {\n if (neighbor != parent) {\n dfs(neighbor, node, d + 1, adj);\n euler.push_back(node);\n depth.push_back(d);\n }\n }\n }\n\n void buildSparseTable() {\n int m = euler.size();\n logN = log2(m) + 1;\n sparseTable.assign(m, vector<int>(logN));\n\n // Initialize the sparse table with the depth indices\n for (int i = 0; i < m; i++) {\n sparseTable[i][0] = i;\n }\n\n // Build the Sparse Table\n for (int j = 1; (1 << j) <= m; j++) {\n for (int i = 0; i + (1 << j) <= m; i++) {\n int left = sparseTable[i][j-1];\n int right = sparseTable[i + (1 << (j-1))][j-1];\n sparseTable[i][j] = (depth[left] < depth[right]) ? left : right;\n }\n }\n }\n\n int querySparseTable(int l, int r) {\n int length = r - l + 1;\n int j = log2(length);\n int left = sparseTable[l][j];\n int right = sparseTable[r - (1 << j) + 1][j];\n return (depth[left] < depth[right]) ? left : right;\n }\n\n public:\n LCA(const vector<vector<int>>& adj, int root) {\n n = adj.size();\n euler.reserve(2 * n - 1);\n depth.reserve(2 * n - 1);\n firstOccurrence.assign(n, -1);\n\n // Perform Euler Tour\n dfs(root, -1, 0, adj);\n\n // Build the Sparse Table based on the depth array\n buildSparseTable();\n }\n\n int getLCA(int u, int v) {\n int left = firstOccurrence[u];\n int right = firstOccurrence[v];\n if (left > right) swap(left, right);\n int idx = querySparseTable(left, right);\n return euler[idx];\n }\n };\n\n // template ends\n\n vector<vector<int> > v;\n void dfs(int ver, int par, vector<vector<pair<int, int> > >& g){\n for(auto it: g[ver]){\n int child = it.first, wt = it.second;\n if(child == par) continue;\n for(int i = 1; i <= 26; i++) v[child][i] += v[ver][i];\n v[child][wt] += 1;\n dfs(child, ver, g);\n }\n }\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n v.resize(n, vector<int>(27, 0));\n for(int i = 0; i < n; i++) v[i].resize(27);\n vector<vector<pair<int, int> > > g(n);\n vector<vector<int> > adj(n);\n for(auto it: edges){\n g[it[0]].push_back({it[1], it[2]});\n adj[it[0]].push_back(it[1]);\n g[it[1]].push_back({it[0], it[2]});\n adj[it[1]].push_back(it[0]);\n }\n\n LCA lca(adj, 0);\n\n dfs(0, -1, g);\n\n // for(int i = 0; i < n; i++){\n // for(int j = 1; j <= 8; j++) cout << v[i][j] << \' \'; cout << endl;\n // }\n\n vector<int> ans;\n\n for(auto p: queries){\n int i = p[0], j = p[1];\n vector<int> cnt(27);\n int maxi = 0;\n int tot = 0;\n for(int k = 1; k <= 26; k++){\n cnt[k] += v[i][k] + v[j][k];\n }\n // cout << lca.getLCA(i, j) << endl;\n for(int k = 1; k <= 26; k++){\n cnt[k] -= 2*v[lca.getLCA(i, j)][k];\n }\n for(int k = 1; k <= 26; k++){\n maxi = max(maxi, cnt[k]);\n tot += cnt[k];\n }\n ans.push_back(tot-maxi);\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting Solution | binary-lifting-solution-by-dnanper-wpfw | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dnanper | NORMAL | 2024-08-28T03:55:05.289244+00:00 | 2024-08-28T03:55:05.289264+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n\nclass Solution {\npublic: \n int up[10005][16], h[10005];\n int n, m;\n vector<vector<pair<int,int>>> adj = vector<vector<pair<int,int>>>(10005);\n vector<vector<int>> weight = vector<vector<int>>(10005, vector<int>(27, 0) );\n void dfs(int u, int p, int h_)\n {\n up[u][0] = p;\n h[u] = h_;\n for ( auto &x : adj[u] )\n {\n int v = x.first, w = x.second;\n if ( p == v) continue;\n weight[v] = weight[u];\n weight[v][w] ++;\n dfs(v, u, h_+1);\n }\n }\n void preprocess()\n {\n for ( int j = 1; j < m; j++)\n {\n for ( int i = 0; i < n; i++ )\n {\n if ( up[i][j-1] == -1 ) up[i][j] = -1;\n else up[i][j] = up[up[i][j-1]][j-1];\n }\n }\n }\n int lca(int a, int b)\n {\n if ( h[a] > h[b] ) swap(a, b);\n int k = h[b] - h[a];\n for ( int j=0; (1<<j) <= k; j++)\n {\n if ( k&(1<<j) ) b = up[b][j];\n if ( b==-1 ) break;\n }\n if ( a == b ) return a;\n int l = (int)log2(h[a]);\n for ( int j=l; j >=0; j--)\n if ( up[a][j] != up[b][j] ) a = up[a][j], b = up[b][j]; \n return up[a][0];\n }\n vector<int> minOperationsQueries(int N, vector<vector<int>>& edges, vector<vector<int>>& queries) \n {\n n = N, m = (int)log2(n) + 1;\n for ( auto& e : edges)\n {\n adj[e[0]].push_back(make_pair(e[1], e[2]));\n adj[e[1]].push_back(make_pair(e[0], e[2]));\n }\n dfs(0,-1,0);\n preprocess();\n vector<int> res;\n int m = queries.size();\n int i = 0;\n while ( i < m )\n {\n int a = queries[i][0], b = queries[i][1];\n int act = lca(a, b);\n int tmp = 0;\n for ( int k = 1; k < 27; k++)\n tmp = max(tmp, weight[a][k] + weight[b][k] - 2*weight[act][k]); \n int ans = h[a] + h[b] - 2*h[act] - tmp;\n res.push_back(ans);\n i++;\n } \n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary-Lifting Approach | LCA | Easy to understand | C++ | binary-lifting-approach-lca-easy-to-unde-8kfe | \n# Approach\nHi,I\'m Khelan Mendapara from IIT BHU ECE\'25 and this is my first solution so you may find couple of mistakes.I tried by my own but couldn\'t sol | Utavaliyo | NORMAL | 2024-08-23T11:56:16.925792+00:00 | 2024-08-23T11:56:16.925828+00:00 | 7 | false | \n# Approach\nHi,I\'m Khelan Mendapara from IIT BHU ECE\'25 and this is my first solution so you may find couple of mistakes.I tried by my own but couldn\'t solve it. So I saw hints and tried to follow what the hints were asking for.\n\nHints given were:\n1. Root the tree at any node.\n2. Define a 2D array freq[node][weight] which saves the frequency of each edge weight on the path from the root to each node.\n3. The frequency of edge weight w on the path from a to b is equal to freq[a][w] + freq[b][w] - freq[lca(a,b)][w] * 2, where lca(a,b) is the lowest common ancestor of a and b in the tree.\n4. lca(a,b) can be calculated using binary lifting algorithm or Tarjan algorithm.\n\nHence,\n- I rooted the tree with Node with value 0. \n- Secondly, traversed whole graph by dfs function and store some basic information like level of each node, parent of each node and freq matrix for further calculations. \n- Then I applied the logic given in hints section.\n\n<!-- Describe your approach to solving the problem. -->\n**Variable Explanation**: \np[node][i]: node\'s 2^i th parent.\nfreq[node][weight]: which saves the frequency of each edge weight on the path from the root to each node.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\nvoid dfs(int i,vector<int> &vis,vector<int> &par,vector<pair<int,int>> adj[],vector<vector<int>> &freq,vector<int> &lvl){\n vis[i]=1;\n for(auto it:adj[i]){\n int child=it.first;\n int wt=it.second;\n if(!vis[child]){\n par[child]=i;\n for (int w = 1; w <= 26; ++w) {\n freq[child][w] = freq[i][w];\n }\n freq[child][wt]++;\n lvl[child]=lvl[i]+1;\n dfs(child,vis,par,adj,freq,lvl);\n }\n }\n}\nint kthpar(int node,int k,vector<vector<int>> &p){\n // if(k==0){\n // return node;\n // }\n for(int i=0;i<20;i++){\n if(k &(1<<i)){\n node=p[node][i];\n if(node==-1){\n return -1;\n }\n }\n }\n return node;\n}\nint lca(int a,int b,vector<vector<int>> &p,vector<int> &lvl){\n if(lvl[a]>lvl[b]){\n swap(a, b);\n }\n int dif=lvl[b]-lvl[a];\n b=kthpar(b,dif,p);\n if(a==b){\n return a;\n }\n for(int i=19;i>=0;i--){\n if(p[a][i]!=-1 and p[a][i]!=p[b][i]){\n a=p[a][i];\n b=p[b][i];\n }\n }\n return p[a][0];\n}\n vector<int> minOperationsQueries(int n, vector<vector<int>>& e, vector<vector<int>>& q) {\n vector<pair<int,int>> adj[n];\n vector<int> par(n,-1),vis(n,0),lvl(n,0);\n \n for(auto it:e){\n int u=it[0],v=it[1],w=it[2];\n adj[u].push_back({v,w});\n adj[v].push_back({u,w});\n }\n \n vector<vector<int>> p(n,vector<int>(20,-1)),freq(n,vector<int>(27,0));\n dfs(0,vis,par,adj,freq,lvl);\n for(int i=0;i<n;i++){\n p[i][0]=par[i];\n }\n for(int k=1;k<20;k++){\n for(int i=0;i<n;i++){\n int temp=p[i][k-1];\n if(temp!=-1){\n p[i][k]=p[temp][k-1];\n }\n }\n }\n vector<int> ans;\n for(auto it:q){\n int u=it[0],v=it[1];\n int LCA=lca(u,v,p,lvl);\n int maxi=0,tot=0;\n for(int w=1;w<=26;w++){\n int count = freq[u][w] + freq[v][w] - 2 * freq[LCA][w];\n tot += count;\n maxi = max(maxi, count);\n }\n ans.push_back(tot-maxi);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting | binary-lifting-by-ishaankulkarni11-e1nw | \n\n# Code\ncpp []\nclass Solution {\n\npublic:\n void dfs(int node,int pp,vector<pair<int,int>>adj[],vector<vector<int>>&par,vector<int>&depth,vector<vector | ishaankulkarni11 | NORMAL | 2024-08-20T11:01:23.651978+00:00 | 2024-08-20T11:01:23.652017+00:00 | 1 | false | \n\n# Code\n```cpp []\nclass Solution {\n\npublic:\n void dfs(int node,int pp,vector<pair<int,int>>adj[],vector<vector<int>>&par,vector<int>&depth,vector<vector<int>>&dp){\n par[node][0] = pp;\n if(pp!=-1){\n for(int i = 1;i<27;++i){\n dp[node][i] += dp[pp][i];\n }\n }\n if(pp!=-1) depth[node] = depth[pp]+1;\n for(auto it:adj[node]){\n if(it.first!=pp){\n dp[it.first][it.second] += 1;\n dfs(it.first,node,adj,par,depth,dp);\n }\n }\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n if(n==1) return {0};\n vector<vector<int>>par(n,vector<int>(20,-1));\n vector<pair<int,int>>adj[n];\n vector<vector<int>>dp(n,vector<int>(27,0)); \n //for a node n and edWt w dp[node][w] denotes freq of w int the path from root to node\n for(auto it:edges){\n adj[it[0]].push_back(make_pair(it[1],it[2]));\n adj[it[1]].push_back(make_pair(it[0],it[2]));\n }\n vector<int>depth(n,0);\n set<int>st;\n for(auto it:edges){\n st.insert(it[2]);\n }\n dfs(0,-1,adj,par,depth,dp);\n \n \n for(int x = 1;x<20;++x){\n for(int node = 0;node<n;++node){\n if(par[node][x-1]!=-1){\n par[node][x] = par[par[node][x-1]][x-1];\n }\n else{\n par[node][x] = -1;\n }\n }\n }\n vector<int>ans(queries.size());\n for(int i = 0;i<queries.size();++i){\n int a = queries[i][0],b = queries[i][1];\n if(depth[a]>depth[b]) swap(a,b);\n int k = depth[b]-depth[a];\n for(int i = 0;i<20;++i){\n if(k&(1LL<<i)){\n b = par[b][i];\n }\n }\n int lca = -1;\n if(a==b){\n lca = a;\n }\n else{\n for(int i = 19;i>=0;i--){\n if(par[a][i]!=par[b][i]){\n a = par[a][i];\n b = par[b][i];\n }\n }\n lca = par[a][0];\n }\n a = queries[i][0],b = queries[i][1];\n int maxi = INT_MIN;\n int cnt = 0;\n for(auto it:st){\n int fa = dp[a][it]-dp[lca][it];\n int fb = dp[b][it]-dp[lca][it];\n if(fa==0 && fb==0){\n \n }\n else{\n cnt += fa;\n cnt += fb;\n }\n maxi = max(maxi,fa+fb);\n }\n ans[i] = cnt-maxi;\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA + Counters | lca-counters-by-sank555-r2ut | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sank555 | NORMAL | 2024-07-06T05:47:01.445638+00:00 | 2024-07-06T05:47:01.445666+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(Q*logN)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n\n def preprocess_lca(n, root, adj, weights):\n LOG = math.ceil(math.log2(n)) + 1\n depth = [0] * n\n up = [[-1] * LOG for _ in range(n)]\n weight_counters = [Counter() for _ in range(n)] \n\n def go(i, p):\n if p != -1:\n weight_counters[i] = weight_counters[p].copy()\n weight_counters[i][weights[(p, i)]] += 1\n up[i][0] = p\n for j in range(1, LOG):\n if up[i][j - 1] != -1:\n up[i][j] = up[up[i][j - 1]][j - 1]\n for v in adj[i]:\n if v != p:\n depth[v] = depth[i] + 1\n go(v, i)\n\n go(root, -1)\n return depth, up, weight_counters, LOG\n\n def lca(u, v, depth, up, LOG):\n if depth[u] < depth[v]:\n u, v = v, u\n \n diff = depth[u] - depth[v]\n for i in range(LOG):\n if (diff >> i) & 1:\n u = up[u][i]\n \n if u == v:\n return u\n \n for i in range(LOG - 1, -1, -1):\n if up[u][i] != up[v][i]:\n u = up[u][i]\n v = up[v][i]\n \n return up[u][0]\n\n def path_weight_frequencies(u, v, depth, up, weight_counters, LOG):\n lca_node = lca(u, v, depth, up, LOG)\n u_weights = weight_counters[u]\n v_weights = weight_counters[v]\n lca_weights = weight_counters[lca_node]\n path_weights = u_weights + v_weights - Counter({w: 2 * lca_weights[w] for w in lca_weights})\n \n return path_weights\n adj = defaultdict(list)\n weights = defaultdict()\n for u,v,w in edges:\n weights[(u,v)] = weights[(v,u)] = w\n adj[v].append(u)\n adj[u].append(v)\n depth, up, weight_counters, LOG = preprocess_lca(n,0,adj,weights)\n ans = []\n for u,v in queries:\n if u==v:\n ans.append(0)\n else:\n c = path_weight_frequencies(u,v,depth,up,weight_counters,LOG)\n a = sum(c.values()) - max(c.values())\n ans.append(a)\n return ans\n\n``` | 0 | 0 | ['Tree', 'Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA + DP | lca-dp-by-karthikeysaxena-ldww | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | karthikeysaxena | NORMAL | 2024-07-05T13:48:19.253038+00:00 | 2024-07-05T13:48:19.253062+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n void dfs(int u, int p, vector<int> &lev, vector<vector<pair<int, int>>> &adj, vector<vector<int>> &pathWt, vector<vector<int>> &dp) {\n if (p >= 0) lev[u] = lev[p] + 1;\n\n dp[u][0] = p;\n\n for (int i = 1; i < 18; i++) {\n if (dp[u][i - 1] < 0) dp[u][i] = -1;\n else dp[u][i] = dp[dp[u][i - 1]][i - 1];\n }\n\n for (auto v: adj[u]) {\n if (v.first == p) continue;\n pathWt[v.first] = pathWt[u];\n pathWt[v.first][v.second] = pathWt[u][v.second] + 1;\n dfs(v.first, u, lev, adj, pathWt, dp);\n }\n }\n\n int getLCA(int x, int y, vector<int> &lev, vector<vector<int>> &dp) {\n if (lev[y] > lev[x]) swap(x, y);\n int diff = lev[x] - lev[y];\n\n // bringing x and y to same level\n for (int i = 0; i < 18; i++) {\n if (diff & (1 << i)) {\n x = dp[x][i];\n }\n }\n\n if (x == y) return x;\n\n // converge x and y towards LCA\n for (int i = 17; i >= 0; i--) {\n if (dp[x][i] != dp[y][i]) {\n x = dp[x][i];\n y = dp[y][i];\n }\n }\n\n return dp[x][0];\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& e, vector<vector<int>>& q) {\n vector<vector<int>> pathWt(n, vector<int> (27, 0)), dp(n, vector<int> (18, -1));\n vector<int> lev(n), ans;\n\n vector<vector<pair<int, int>>> adj(n);\n\n for (auto x: e) {\n adj[x[0]].push_back(make_pair(x[1], x[2]));\n adj[x[1]].push_back(make_pair(x[0], x[2]));\n }\n\n dfs(0, -1, lev, adj, pathWt, dp);\n\n for (auto x: q) {\n int a = x[0], b = x[1];\n int lca = getLCA(a, b, lev, dp);\n\n int val = 0, tot = (lev[a] - lev[lca]) + (lev[b] - lev[lca]);\n for (int i = 0; i < 27; i++) {\n int wt = (pathWt[a][i] - pathWt[lca][i]) + (pathWt[b][i] - pathWt[lca][i]);\n val = max(val, wt);\n }\n\n ans.push_back(tot - val);\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Easy soln | easy-soln-by-aggarwalsiddharth49-biba | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | aggarwalsiddharth49 | NORMAL | 2024-06-29T08:23:59.875317+00:00 | 2024-06-29T08:23:59.875345+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int node, int par, vector<vector<pair<int, int>>>& adj,\n vector<vector<int>>& up, vector<int>& depth,\n vector<vector<int>>& mp) {\n up[node][0] = par;\n for (int i = 1; i < 20; i++) {\n int halfpar = up[node][i - 1];\n up[node][i] = up[halfpar][i - 1];\n }\n for (auto child : adj[node]) {\n if (child.first == par)continue;\n depth[child.first] = 1 + depth[node];\n mp[child.first]= mp[node];\n mp[child.first][child.second]++;\n dfs(child.first, node, adj, up, depth, mp);\n }\n }\n int kthparent(int node, int k, vector<vector<int>>& up) {\n for (int i = 19; i >= 0; i--) {\n if (k & ( 1<<i)) node = up[node][i];\n }\n return node;\n }\n int lca(int a, int b, vector<vector<int>>& up ,vector<int >&depth ) {\n if (depth[b] > depth[a])\n swap(a, b);\n int climb = depth[a] - depth[b];\n a = kthparent(a , climb , up );\n if (a == b)\n return a;\n for (int i = 19; i >= 0; i--) {\n if (up[a][i] == up[b][i])\n continue;\n a = up[a][i];\n b = up[b][i];\n }\n return up[a][0];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges,\n vector<vector<int>>& queries) {\n vector<vector<pair<int, int>>> adj(n);\n vector<vector<int>> up(n, vector<int>(20 , 0 ));\n vector<vector<int>> mp(n, vector<int>(27, 0));\n vector<int> ans;\n vector<int> depth(n, 0);\n for (auto it : edges) {\n adj[it[0]].push_back({it[1], it[2]});\n adj[it[1]].push_back({it[0], it[2]});\n }\n dfs(0, 0, adj, up, depth, mp);\n\n for (int i = 0; i < queries.size(); i++) {\n int s = queries[i][0];\n int e = queries[i][1];\n int leastCommon = lca(s, e, up , depth);\n vector<int> temp(27, 0);\n for (int i = 0; i < 27; i++) {\n temp[i] += mp[s][i];\n temp[i] += mp[e][i];\n temp[i] -= 2 * mp[leastCommon][i];\n }\n\n int maxi = INT_MIN;\n int sum = 0;\n for (int i = 0; i < 27; i++) {\n sum += temp[i];\n maxi = max(maxi, temp[i]);\n }\n sum = sum - maxi;\n ans.push_back( sum );\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | 👍Runtime 312 ms Beats 100.00% of users with Go | runtime-312-ms-beats-10000-of-users-with-ztjb | Code\n\n\ntype Solution struct {\n\tgraph [][][2]int\n\tparentOf []int\n\tdepthLevel []int\n\twtFreq [][]int\n\tparentOfMatrix [][]in | pvt2024 | NORMAL | 2024-06-02T01:03:22.840162+00:00 | 2024-06-02T01:03:22.840189+00:00 | 2 | false | # Code\n```\n\ntype Solution struct {\n\tgraph [][][2]int\n\tparentOf []int\n\tdepthLevel []int\n\twtFreq [][]int\n\tparentOfMatrix [][]int\n}\n\nfunc minOperationsQueries(n int, edges [][]int, queries [][]int) []int {\n\ts := &Solution{\n\t\tgraph: make([][][2]int, n),\n\t\tparentOf: make([]int, n),\n\t\tdepthLevel: make([]int, n),\n\t\twtFreq: make([][]int, n),\n\t}\n\tfor i := range s.wtFreq {\n\t\ts.wtFreq[i] = make([]int, 27)\n\t}\n\n\tfor _, edge := range edges {\n\t\ts.graph[edge[0]] = append(s.graph[edge[0]], [2]int{edge[1], edge[2]})\n\t\ts.graph[edge[1]] = append(s.graph[edge[1]], [2]int{edge[0], edge[2]})\n\t}\n\n\ts.populateData(0, -1, 1, make([]int, 27))\n\ts.parentOf[0] = 0\n\ts.parentOfMatrix = s.buildParentOfMatrix()\n\n\tresults := make([]int, len(queries))\n\n\tfor q, query := range queries {\n\t\tu, v := query[0], query[1]\n\t\tlca := s.lcaUsingBinaryLifting(u, v)\n\n\t\tmaxFreqUV, totalWtFreqUV := 0, 0\n\n\t\tfor wtVal := 1; wtVal <= 26; wtVal++ {\n\t\t\tfreq := s.wtFreq[lca][wtVal]\n\t\t\tfreqU := s.wtFreq[u][wtVal]\n\t\t\tfreqV := s.wtFreq[v][wtVal]\n\n\t\t\ttotalWtFreqUV += freqU + freqV - 2*freq\n\n\t\t\tif freqU+freqV-2*freq > maxFreqUV {\n\t\t\t\tmaxFreqUV = freqU + freqV - 2*freq\n\t\t\t}\n\t\t}\n\n\t\tresults[q] = totalWtFreqUV - maxFreqUV\n\t}\n\n\treturn results\n}\n\nfunc (s *Solution) lcaUsingBinaryLifting(u, v int) int {\n\tif s.depthLevel[u] > s.depthLevel[v] {\n\t\treturn s.lcaUsingBinaryLifting(v, u)\n\t}\n\n\tdepthLevelDiff := s.depthLevel[v] - s.depthLevel[u]\n\n\tfor bitPos := 0; bitPos < 31; bitPos++ {\n\t\tif (depthLevelDiff & (1 << bitPos)) != 0 {\n\t\t\tv = s.parentOfMatrix[bitPos][v]\n\t\t}\n\t}\n\n\tif u == v {\n\t\treturn v\n\t}\n\n\tfor bitPos := 30; bitPos >= 0; bitPos-- {\n\t\tif s.parentOfMatrix[bitPos][u] != s.parentOfMatrix[bitPos][v] {\n\t\t\tu = s.parentOfMatrix[bitPos][u]\n\t\t\tv = s.parentOfMatrix[bitPos][v]\n\t\t}\n\t}\n\n\treturn s.parentOfMatrix[0][v]\n}\n\nfunc (s *Solution) populateData(node, par, level int, wts []int) {\n\ts.depthLevel[node] = level\n\ts.parentOf[node] = par\n\n\tcopy(s.wtFreq[node], wts)\n\n\tfor _, child := range s.graph[node] {\n\t\tif child[0] == par {\n\t\t\tcontinue\n\t\t}\n\n\t\twts[child[1]]++\n\t\ts.populateData(child[0], node, level+1, wts)\n\t\twts[child[1]]--\n\t}\n}\n\nfunc (s *Solution) buildParentOfMatrix() [][]int {\n\tn, limit := len(s.parentOf), 31\n\tparMat := make([][]int, limit)\n\tfor i := range parMat {\n\t\tparMat[i] = make([]int, n)\n\t}\n\n\tcopy(parMat[0], s.parentOf)\n\n\tfor bitPos := 1; bitPos < limit; bitPos++ {\n\t\tfor indx := 0; indx < n; indx++ {\n\t\t\tprevParent := parMat[bitPos-1][indx]\n\t\t\tparMat[bitPos][indx] = parMat[bitPos-1][prevParent]\n\t\t}\n\t}\n\n\treturn parMat\n}\n``` | 0 | 0 | ['Go'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA | lca-by-afterfm-gkz7 | \n# Code\n\nclass Solution {\npublic:\n void count_edges(int node, int& parent, vector<pair<int,int>> adj[], vector<vector<int>>& freq, int n, vector<int>& t | cactuz_blues | NORMAL | 2024-05-29T05:40:46.708030+00:00 | 2024-05-29T05:40:46.708051+00:00 | 2 | false | \n# Code\n```\nclass Solution {\npublic:\n void count_edges(int node, int& parent, vector<pair<int,int>> adj[], vector<vector<int>>& freq, int n, vector<int>& temp)\n {\n for(auto child: adj[node])\n {\n if(child.first==parent) continue;\n int wt=child.second;\n temp[wt]++;\n freq[child.first]=temp;\n count_edges(child.first,node,adj,freq,n,temp);\n temp[wt]--;\n }\n }\n void find_ancestors(int node, int& parent, vector<vector<int>>& ancestors, int n, vector<int>& depth, vector<pair<int,int>> adj[])\n{\n for(auto child: adj[node])\n {\n if(child.first==parent) continue;\n ancestors[child.first][0]=node;\n depth[child.first]=depth[node]+1;\n for(int i=1;i<21;i++)\n {\n ancestors[child.first][i]=ancestors[ancestors[child.first][i-1]][i-1];\n }\n find_ancestors(child.first,node,ancestors,n,depth,adj);\n }\n}\n int find_lca(int a, int b, vector<int>& depth, vector<vector<int>>& ancestors)\n{\n if(depth[b]>depth[a]) swap(a,b);\n int k=depth[a]-depth[b];\n for(int i=20;i>=0;i--)\n {\n if(k&(1<<i))\n {\n a=ancestors[a][i];\n }\n }\n if(a==b) return b;\n for(int i=20;i>=0;i--)\n {\n if(ancestors[a][i]!=ancestors[b][i])\n {\n a=ancestors[a][i];\n b=ancestors[b][i];\n }\n }\n return ancestors[a][0];\n}\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<pair<int,int>> adj[n];\n for(int i=0;i<n-1;i++)\n {\n int u=edges[i][0];\n int v=edges[i][1];\n int wt=edges[i][2];\n adj[u].push_back({v,wt});\n adj[v].push_back({u,wt});\n }\n vector<vector<int>> freq(n,vector<int>(27));\n for(int i=1;i<=26;i++) freq[0][i]=0;\n vector<int> temp(27);\n int parent=-1;\n count_edges(0,parent,adj,freq,n,temp);\n vector<int> depth(n);\n vector<vector<int>> ancestors(n,vector<int>(21));\n find_ancestors(0,parent,ancestors,n,depth,adj);\n int q=queries.size();\n vector<int> ans(q);\n for(int i=0;i<q;i++)\n {\n int u=queries[i][0];\n int v=queries[i][1];\n int lca=find_lca(u,v,depth,ancestors);\n int maxi=0;\n int total=0;\n for(int j=1;j<=26;j++)\n {\n int cnt=freq[u][j]+freq[v][j]-2*freq[lca][j];\n if(cnt) total+=cnt;\n maxi=max(maxi,cnt);\n }\n ans[i]=total-maxi;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA And Binary Lifting in Python. Complete Intuition and Explanation of concepts | lca-and-binary-lifting-in-python-complet-5lqc | Intuition\n Describe your first thoughts on how to solve this problem. \n- Given two nodes, we need to find minimum operations to make all edge weights equal\n- | silencer312 | NORMAL | 2024-05-24T20:43:46.567440+00:00 | 2024-05-24T23:35:58.798418+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Given two nodes, we need to find minimum operations to make all edge weights equal\n- This is the crux of the problem, but to do this efficiently, we need to use a couple of techniques\n- First, we need to find the path from node a to node b and then the edge weights, and need to do it efficiently.\n- We cannot use DFS for every query since we have large number of queries 10^4 and also n <= 10^4\n- So we need to think in terms of logarithmic time, and a technique that can help is binary lifting\n- Binary lifting is a dynamic programming technique useful to find the kth ancestor of a node in a tree with unique paths\n- And using Binary lifting, we can find the LCA of the nodes. Using LCA as a midpoint between the two nodes, we are able to find the edges and the weights between the two nodes. \n- Using LCA, we calculate the edges or distance between a and b. Now to find the operations needed, we somehow need to know the edge weights\n- For this, we keep a weights 2D array weights[i][j] where j is the weight, i is node and weights[i][j] is the total number of weights j seen from root to node i.\n- This is basically a count of weights. We then use LCA to find the weights between the two nodes a and b\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- This problem can be divided into multiple sub-problems. Lets tackle each one separately.\n\n#### Binary Lifting:\n- Lets talk about this technique first. \n- To find the Kth Ancestor of a node, we will look up k times. If we have a parent array, we look up k times, or use dfs to create a parent array\n- Or something similar to a linear time search. But for large trees and large K\'s this is too much time\n- So we need a way to do this search (or jump) in logK time.\n- We will jump in powers of 2. So a jump of i means to jump 2^i. For i = 0, this is the 1st ancestor which is just the immediate parent because 2^0 = 1\n- For i = 2, we jump 2^2 = 4 times. Max we can jump is the depth of the tree = M\n- Note this property: 2^K = 2.2^(k-1) = 2^k-1 + 2^k-1. This means if we want to find the jump of K, we jump k-1 twice. Important for calculations. This means we jump k-1, and from that node jump k-1 again\n- We chose powers of 2 to jump because every number can be represented in powers of 2. Think binary numbers\n- So the concept of binary lifting means to pre-compute all the k jumps for each node, and then we can find the kth jump in logN time\n- Now the question comes how to pre-compute the jumps efficiently. We dont want to do it in linear time else it beats our purpose.\n- We will compute all values top down. Means we will calculate the jumps for the root first, then its children and so on\n- We will store the jumps in a 2D Array dp[i][j] where i = ith jump and j = node j. Here ith jump = 2^i jumps. So i = 0 means just the parent\n- And to calculate dp[i][j], we use the above property\ndp[i][j] = dp[i-1][dp[i-1][j]]. Or simply dp[i-1][x] where x = dp[i-1][j]. This is same as jumping i-1 times from node j. Call that node x. Then jump i-1 times from node x\n- This way we can calculate the jumps N.M time, where M=height = logN\n- Now to get the Kth ancestor? Because that is the problem we are trying to solve using binary lifting right?\nk=10th ancestor or 10th jump = 2^3 + 2^1 jump\n- Take log-base2-K, this will give the number of jumps. Say K = 10, we get log(10) = i = 3 (take int)\n- Now calculate the 3rd jump for node. And next jump will be calculate from this node. Also adjust k, we gotta remove the jumps we did\n- Since K was 10, and we did 2^i jump, remove that using bit shift. k -= (1 << i) where << means left shift by i (here 3). This is same as multiplying 1 * 2^3 = 8\n- So we do k-8, and k = 2 now. Take log(2) = 1. So we make 1 jump from the node. dp[1][node]. And k becomes 0 now, so we stop and get the k = 10th ancestor\n\n#### Finding LCA:\n- LCA or Lowest Common Ancestor is the first common ancestor of nodes a and b on the path to the root. \n- It can be node a or b or one of their parents.\n- For LCA, this holds true: \n- distance(a,b) = distance(a) + distance(b) - 2*distance(LCA(a,b))\n- Think about it, We calculate distance of each node from root, add them. Then realize we added distance from root to LCA twice, so subtract\n- To find the LCA, we keep going up from the two nodes and stop when the parents of the two nodes are same. At that point, LCA is the parent of either of the node.\n- To do this efficiently, we first need to make the depths of both the nodes same. So have to move one node up to the same depth.\n- Then we check if both the nodes are same, this means one node was descendant of the other, and we have our LCA\n- Else, we then try to jump from both nodes and do this to repeatedyly until we find that parents of both nodes are equal.\n- We start with the biggest jump we can take, and then look for smaller jumps where the nodes are not equal\n- At that point, both their parents are the LCA so can return any one\n- Lets see how we do this efficiently using bit manipulation\n- First to move the node at the same depth, we find the depth difference and use bit masking to get the set bits of the difference, and then take that jump from the node.\n- The height of our tree (and length of row of the DP array) is m. So we start from the max height of the tree\n- Lets understand the bit operation we are doing here. We can do a linear loop to make them same heights, but bit operation works in log2 time\n- 1 << x means take number 1 and left shift it x times. Equivalent to 1 * 2^x\n- Lets see what this means. 00001 -> 1, left shift this one times -> 00010. Again left shift -> 00100\n- Remember the & operator, 1 & x = 1. 0 & x = 0. This is the concept of bitmasking we will use\n- Now take a number 8 and & it with a bit shifted number we talked about. So 8 & 1 << 2 = 8 & 100 = 1000 & 100 both in binary = 0000 = 0. So we get 0\n- Do 8 & 1 << 3 = 8 & 8 = 1000 & 1000 = 1000. Which is non zero, we are not interested in the value, only if it is zero or not\n- When it was 0, it meant that the 2nd bit was not set. Before we did & with 1<<2 (shifting 2 times)\n- 1 << 3 was not zero, means 3rd bit was set so we get ans as 8, when shift was 3 times\n- Now take a number 12 and run i in range (1 to 20). Do 12 & (1 << i). For each i, we left shift the number 1\n- So we are actually doing this for each bit in 12. 12 = 1100. So for i = 2 and 3, we will get non zero answer\n- And our answer will be 100 and 1000 = 4 + 8 = 12. So we are extracting the bits from the number 12\n- So when we do diff & (1 << i), we are actually extracting diff into its binary components\n- see 12 = 2^3 + 2^2. When we find the k = 12th ancestor, we need this exact thing. We can also do this using logbase2 12\n- log12 = 3 and remaining number = 12-8 = 4. log4=2. So remember we make jumps of 3 and then 2\n- This is exactly what our bit manipulation gave us too. Since we are running i from m-1 to 1, we first find the left most bit\n- For 12 this will be i = 3. Means for i = 3, diff & (1 << i) will be non zero. And remember i = 3 means ith binary jump we need to take\n- So to bring this node to the level diff above itself, we first take the 3rd jump parent.\n- Then as i decreases, we get the next bit that was set and take that jump. Eventually, we bring the node up by diff depth same as other node\n- Imagine diff = 13, = 1101. We will make jumps of 3, 2, and 1. This is exactly same as the log thing we did, just in bit manipulation\n- And works in log time as well.\n- To find the LCA, we use a similar technique by taking the longest jumps we can take where parents are not equal, then we try smaller jumps until we end up just below the LCA\n- At that point we need the parent = 0th jump from the node\n\n#### DFS - Extracting info from the tree:\n- Our Binary Lifting and LCA assumed we have the depth information and parents information of the tree\n- But in this graph, we dont. So we create adj list from edges first\n- Then do a dfs from any node. Yes we can root the tree at any node, it just affects the depths and LCA nodes, but we still get the right information needed from the graph\n- Also here since we need to know the weights that was taken to reach to a node from the root, we will create that matrix too\n- We will have a weights[i][j] where i = node and j = weight.\n- We have weights in the range 1-26, so will initialize a weights array for each node of length 27. 27 because, we can use index 1 to 26 to correspond to the weights and dont need to offset for 0 weights.\n- This is a standard dfs call, where we also pass in the current node as the previous node to next call, which fills up the parents[0][j] of node j\n- Depth is just a variable that increases in each call\n- For weights, we first intialize the weights of node 0 with all 0\'s, then for each weight seen in neighbors, we increase the count\n- When going to a neighbor, we copy the current node\'s weights to it, and then increase count based on edge weight\n- Remember since this is undirected graph, we do not want to end up back at parent, so have a check for that too\n\n#### Building Parent matrix for Binary Jumps:\n- As discussed above, we just loop and populate the matrix top down using parents[i][j] = parents[i-1][parents[i-1][j]]\n- Remember since parents[i][j] depends on i - 1 being calculated. If you have understood the technique, you would know that this means to calculate ith jump for node j, you need the (i-1)th jump for node j. Lets call that x. Then you need the (i-1)th jump for node x. But for this to be possible, you need to calculate the (i-1)th jump for all nodes. It is only possible if you loop on jumps in outer loop, and nodes in inner loop. Else you might land on a node x, that has yet not calculated its (i-1)th jump\n- This is the top down appraoch I talked about\n\n#### Processing the query:\n- Now we have everything set up and can calculate the queries efficiently\n- Given nodes u and v, we calculate lca node.\n- Now we can calculate the number of edges between the nodes u and v using the LCA formula on depths\n- no of edges = depth(u) + depth(v) - 2*depth(lca)\n- Next we iterate on all the weights, and then try to make all the edges between nodes u and v of this weight W\n- Operations needed will be (no of edges) - (count of edges with weight W). The remaining edges are the number of operations\n- We can get count of edges with weight W between nodes u and v using the LCA formula on the weights matrix this time\n- This gives us operatations needed for weight W, we do this for all weights and take the minimum to get the answer for the given query\n\n\n# Complexity\n### Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- O(N) for initialization of 2D arrays and graph where N = number of nodes and we have n-1 edges\n- O(N) for dfs creating graph params - finding depth, first parent and creating weights array. Linear because the dfs processed each node once. There is some overhead because we copy the weights list of parent node in the dfs call. Let W be the total weights = 26. So, O(WN) to be more precise\n- O(M.N) for building the parents array where M = max depth of tree = logN. So O(NlogN)\n- O(M + W) to process each query. We need O(M) to calculate LCA for each query, and then processing loops on all weights which are constant. Rest are constant time operations\n- O(Q(M + W)) total time to process each query\n- Total time: O(N + W.N + M.N + Q.(M + W)) , where N = no of nodes, Q = Max number of queries, M = logN max depth of tree, W = 26 total weights = constant \n- Simplifying, we get O(M.N + Q(M + W)) because M.N dominates over N and W.N. We can also treat W as constant for our problem and since M = logN\n- We get time = O(NlogN + QlogN)\n\n### Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- 2D arrays take space of O(M.N) where M = logN\n- Depth array and graph adj list takes O(N)\n- DFS Call stack O(N)\n- Result array takes O(Q) where Q = no of queries\n- Total space ignoring space for result and simplifying by taking dominant terms = O(MN) = O(NlogN)\n# Code\n\n```\nclass WeightEquilibrium:\n def __init__(self, n):\n self.m = 1 + math.ceil(math.log2(2 * 1e4)) # constraint on queries\n self.n = n\n self.total_w = 27 # total weights given\n self.root_node = 0 # set root node, any node doesnt matter\n\n self.weights = [None for i in range(n)] # weights[i] is the weights list at node i. Above explanation was reversed. We will later add the weights\n self.parents = [[-1 for i in range(n)] for j in range(self.m)] # parents[i][j] is the ith jump parent of node j (binary jump)\n self.depth = [0 for i in range(n)] # depth of node i\n\n self.graph = collections.defaultdict(list)\n\n\n def create_graph(self, edges):\n for a, b, w in edges:\n self.graph[a].append([b, w])\n self.graph[b].append([a, w])\n\n def initialize_graph_params(self):\n self.weights[self.root_node] = [0] * self.total_w # initialize the weight of root with all 0\'s. The dfs copies this to neighbors and increases weights as seen\n # the benefit of copying one by one is we keep a copy of weights to the parents and just increase the weight to child\n self._dfs(self.root_node, -1, 0) # set 0 as root, -1 as prev of root and 0 depth\n\n def _dfs(self, curr, prev, depth):\n # purpose of this dfs is to calculate depth of each node, weights of each node and populate the first parent of each node parents[0][i] for node i\n\n self.parents[0][curr] = prev # since prev is the node that called this, it is the immediate parent\n self.depth[curr] = depth # depth is the current depth\n\n # now look at neighbors\n for nei, wt in self.graph[curr]:\n if nei == prev:\n continue # since undirected graph, we dont wanna go back to parent, so add a check\n self.weights[nei] = self.weights[curr].copy() # copy the current nodes weight to neighbor\n self.weights[nei][wt] += 1 # and increase the weight count of the edge\n self._dfs(nei, curr, depth + 1) # increase depth and pass current node as prev\n\n def build_parents(self):\n # this is our standard parents calculation where ith jump is (i-1)th jump + (i-1)th jump from the previous node\n for i in range(1, self.m): # loop from index 1, because we already populated 0th jump parents\n for j in range(self.n):\n if self.parents[i - 1][j] == -1:\n self.parents[i][j] = -1\n else:\n self.parents[i][j] = self.parents[i - 1][self.parents[i - 1][j]]\n\n def find_lca(self, u, v):\n if self.depth[v] > self.depth[u]:\n u, v = v, u # make u to be deeper\n diff = self.depth[u] - self.depth[v]\n for i in range(self.m - 1, -1, -1): # the parents array index is 0 to m-1. We start from m-1 to get the leftmost bit first\n if diff & (1 << i):\n u = self.parents[i][u]\n\n # now u and v are at same level\n\n if u == v: # if they are same, means one of them is the ancestor of the other. And can return here\n return u\n\n # if they are not same, we try to bring them to a point, where their parents are equal. Again this is a loop in M time = logN time\n for i in range(self.m - 1, -1, -1): # we start with the largest jump where parents are not equal.\n # We dont take the jump, if the nodes are equal. Because that means we came too far up the tree. We need Lowest since LCA\n # When we see the nodes are not equal, we take that jump. And continue\n # We start with the biggest jump we can take, and then look for smaller jumps where the nodes are not equal\n # At that point, both their parents are the LCA so can return any one\n if self.parents[i][u] != self.parents[i][v]:\n u, v = self.parents[i][u], self.parents[i][v]\n return self.parents[0][u]\n\n def edges_between(self, u, v, lca): # return the edges between u and v given lca node\n return self.depth[u] + self.depth[v] - 2 * self.depth[lca]\n\n def weights_between(self, u, v, lca, w): # return the edges with weight W between u and v given lca node\n return self.weights[u][w] + self.weights[v][w] - 2 * self.weights[lca][w]\n\n def process_query(self, query):\n node1, node2 = query\n lca_node = self.find_lca(node1, node2) # find the lca node of the two nodes\n\n # Check the explanation above for LCA Relation\n no_of_edges = self.edges_between(node1, node2, lca_node) # no of edges between node1 and node2\n min_operations = no_of_edges # to change every weight, this will be the max changes we can make, so can start with this and take minimum\n\n # We will go through each weight, and try to make all other edges equal to that weight from the path from node1 to node2\n # We know count of weights at each node and the LCA. So can again use LCA formula to get the count of weights we are looking at\n # We know the total edges in the path, we get the count of specific weight.\n # To make all other edges of this weight, we can subtract, and take min\n for w in range(1, self.total_w):\n weights_w = self.weights_between(node1, node2, lca_node, w) # these are the total edges with weights w\n # we will make all other edges as this weight\n min_operations = min(min_operations, no_of_edges - weights_w)\n\n return min_operations\n```\n```\nclass Solution:\n \n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n\n wt_eq = WeightEquilibrium(n) # initialize variables\n wt_eq.create_graph(edges) # create graph\n\n wt_eq.initialize_graph_params() # dfs to generate depth, weights and parents\n wt_eq.build_parents() # build all the binary lifting parents\n\n res = []\n for query in queries: # loop on queries to get ans for each\n res.append(wt_eq.process_query(query))\n\n return res\n\n```\n\nProblems for Binary Lifting:\n[1483. Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/)\n[1724. Checking Existence of Edge Length Limited Paths II](https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii/description/)\n[2836. Maximize Value of Function in a Ball Passing Game](https://leetcode.com/problems/maximize-value-of-function-in-a-ball-passing-game/)\n[2846. Minimum Edge Weight Equilibrium Queries in a Tree](https://leetcode.com/problems/minimum-edge-weight-equilibrium-queries-in-a-tree/description/) | 0 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Bitmask', 'Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA (Binary Lifting) + Frequency Table - Beats 90% | lca-binary-lifting-frequency-table-beats-ures | Code\n\nclass Solution {\npublic:\n int LOG = 32;\n vector<int> depth;\n vector<vector<int>> up;\n vector<vector<pair<int, int>>> adj;\n vector<v | summmiiiittttt | NORMAL | 2024-05-21T14:55:53.062553+00:00 | 2024-05-21T14:55:53.062582+00:00 | 8 | false | # Code\n```\nclass Solution {\npublic:\n int LOG = 32;\n vector<int> depth;\n vector<vector<int>> up;\n vector<vector<pair<int, int>>> adj;\n vector<vector<int>> freq;\n\n void build(int node, int parent, int weight) {\n if (node == 0) {\n depth[node] = 1;\n } else {\n depth[node] = depth[parent] + 1;\n freq[node] = freq[parent];\n freq[node][weight]++;\n }\n up[node][0] = parent;\n for (int i = 1; i < LOG; i++) {\n if (up[node][i - 1] != -1)\n up[node][i] = up[up[node][i - 1]][i - 1];\n else\n up[node][i] = -1;\n }\n for (auto &curr : adj[node]) {\n int child = curr.first;\n int wt = curr.second;\n if (child != parent)\n build(child, node, wt);\n }\n }\n\n int lca(int a, int b) {\n if (depth[a] < depth[b])\n swap(a, b);\n int k = depth[a] - depth[b];\n for (int i = LOG - 1; i >= 0; i--) {\n if ((k & (1 << i)))\n a = up[a][i];\n }\n if (a == b)\n return a;\n for (int i = LOG - 1; i >= 0; i--) {\n if (up[a][i] != up[b][i]) {\n a = up[a][i];\n b = up[b][i];\n }\n }\n return up[a][0];\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n adj.resize(n);\n freq.resize(n, vector<int>(27, 0));\n for (auto &e : edges) {\n adj[e[0]].push_back({e[1], e[2]});\n adj[e[1]].push_back({e[0], e[2]});\n }\n depth.resize(n, 0);\n up.resize(n, vector<int>(LOG, -1));\n build(0, -1, 0);\n\n vector<int> ans(queries.size());\n for (int j = 0; j < queries.size(); j++) {\n int a = queries[j][0];\n int b = queries[j][1];\n int x = lca(a, b);\n int max_freq = 0;\n for (int i = 1; i <= 26; i++) {\n max_freq = max(max_freq, freq[a][i] + freq[b][i] - 2 * freq[x][i]);\n }\n ans[j] = depth[a] + depth[b] - 2 * depth[x] - max_freq;\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Python Hard | python-hard-by-lucasschnee-ks5f | \nclass BinaryLifting:\n def __init__(self, n, edges):\n self.n = n\n self.LOG = n.bit_length()\n self.C = 27\n self.graph = defa | lucasschnee | NORMAL | 2024-05-16T13:20:25.993612+00:00 | 2024-05-16T13:20:39.995173+00:00 | 6 | false | ```\nclass BinaryLifting:\n def __init__(self, n, edges):\n self.n = n\n self.LOG = n.bit_length()\n self.C = 27\n self.graph = defaultdict(list)\n self.parent = [[-1] * n for _ in range(self.LOG)]\n self.depth = [0] * n\n self.weight_count = [[0] * self.C for _ in range(n)]\n self._build_graph(edges)\n self._preprocess()\n\n def _build_graph(self, edges):\n for u, v, w in edges:\n self.graph[u].append((v, w))\n self.graph[v].append((u, w))\n\n def _dfs(self, node, par):\n self.parent[0][node] = par\n for neighbor, weight in self.graph[node]:\n if neighbor == par:\n continue\n self.depth[neighbor] = self.depth[node] + 1\n self.weight_count[neighbor] = self.weight_count[node].copy()\n self.weight_count[neighbor][weight] += 1\n self._dfs(neighbor, node)\n\n def _preprocess(self):\n self._dfs(0, -1)\n for i in range(1, self.LOG):\n for j in range(self.n):\n if self.parent[i - 1][j] != -1:\n self.parent[i][j] = self.parent[i - 1][self.parent[i - 1][j]]\n\n def get_kth_ancestor(self, node, k):\n for i in range(self.LOG):\n if k & (1 << i):\n node = self.parent[i][node]\n if node == -1:\n break\n return node\n\n def lca(self, u, v):\n if self.depth[u] < self.depth[v]:\n u, v = v, u\n diff = self.depth[u] - self.depth[v]\n u = self.get_kth_ancestor(u, diff)\n if u == v:\n return u\n for i in range(self.LOG - 1, -1, -1):\n if self.parent[i][u] != self.parent[i][v]:\n u = self.parent[i][u]\n v = self.parent[i][v]\n return self.parent[0][u]\n\n def min_operations_queries(self, queries: List[List[int]]) -> List[int]:\n res = []\n for x, y in queries:\n l = self.lca(x, y)\n length = self.depth[x] + self.depth[y] - 2 * self.depth[l]\n max_z = max(self.weight_count[x][z] + self.weight_count[y][z] - 2 * self.weight_count[l][z] for z in range(self.C))\n res.append(length - max_z)\n return res\n\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n bl = BinaryLifting(n, edges)\n return bl.min_operations_queries(queries)\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Find Lowest common ancestor (LCA) using linear space & constant search time | find-lowest-common-ancestor-lca-using-li-lozz | Intuition\n Describe your first thoughts on how to solve this problem. \nhttps://en.wikipedia.org/wiki/Lowest_common_ancestor\n\n# Approach\n Describe your appr | nguyenquocthao00 | NORMAL | 2024-04-09T10:20:21.186984+00:00 | 2024-04-09T10:20:21.187012+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nhttps://en.wikipedia.org/wiki/Lowest_common_ancestor\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass RMQ:\n def __init__(self, data):\n n=len(data)\n m=[list(range(n))]\n for j in range(1, n.bit_length()):\n prev,cur = m[-1], []\n for i in range(n+1-(1<<j)):\n if data[prev[i]] > data[prev[i+(1<<j-1)]]: cur.append(prev[i+(1<<j-1)])\n else: cur.append(prev[i])\n m.append(cur)\n def query(i,j):\n n=(j-i+1).bit_length()-1\n x,y = m[n][i], m[n][j+1-(1<<n)]\n if data[x]>data[y]: return y\n else: return x\n self.query=query\ndef traverse(root, getnb):\n walk,depth = [], []\n def dp(i,prev, d):\n walk.append(i)\n depth.append(d)\n for j in getnb(i):\n if j==prev: continue\n dp(j,i,d+1)\n walk.append(i)\n depth.append(d)\n dp(root,root,0)\n return walk, depth\nclass LCA:\n def __init__(self, root, getnb):\n walk, depth = traverse(root, getnb)\n mindexes = {}\n for i,v in enumerate(walk):\n if v not in mindexes: mindexes[v]=i\n n = len(walk)\n if n<16:\n rmqtotal = RMQ(depth)\n def query(a,b):\n i,j = mindexes[a], mindexes[b]\n if i>j: i,j=j,i\n return walk[rmqtotal.query(i,j)]\n self.query=query\n return \n blocksize = (n.bit_length() - 1) // 2\n if n%blocksize > 0:\n for _ in range(blocksize - n%blocksize): depth.append(depth[-1]+1)\n def getkey(blocki):\n key=0\n for i in range(blocki*blocksize+1, blocki*blocksize + blocksize):\n key<<=1\n if depth[i-1]<depth[i]: key+=1\n return key\n def create_rmq_from_key(key):\n data = [blocksize]\n for _ in range(blocksize-1):\n if key&1: data.append(data[-1]-1)\n else: data.append(data[-1]+1)\n key>>=1\n data = data[::-1]\n return RMQ(data)\n mblockkey={}\n blockrmq = []\n for i in range(len(depth)//blocksize):\n key = getkey(i)\n if key not in mblockkey: mblockkey[key] = create_rmq_from_key(key)\n blockrmq.append(mblockkey[key])\n data_total=[]\n for i,rmq in enumerate(blockrmq):\n j = i*blocksize + rmq.query(0, blocksize-1)\n data_total.append(depth[j])\n rmqtotal = RMQ(data_total)\n def get_min_from_total(blocki, blockj):\n ind = rmqtotal.query(blocki, blockj)\n return ind*blocksize + blockrmq[ind].query(0, blocksize-1)\n def get_min_node(indexes):\n return walk[min(indexes, key=lambda i: depth[i])]\n def query(a,b):\n i,j = mindexes[a], mindexes[b]\n if i>j: i,j=j,i\n blocki, blockj = i//blocksize, j//blocksize\n if blocki==blockj:\n offset = blocki*blocksize\n return get_min_node([offset + blockrmq[blocki].query(i-offset, j-offset)])\n offset = blocki*blocksize\n indexes = [offset + blockrmq[blocki].query(i-offset, blocksize-1)]\n offset = blockj*blocksize\n indexes.append(offset + blockrmq[blockj].query(0, j-offset))\n if blocki+1<=blockj-1: indexes.append(get_min_from_total(blocki+1, blockj-1))\n return get_min_node(indexes)\n self.query=query\n return\n \nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n m,count = [[] for _ in range(n)], [Counter() for _ in range(n)]\n for a,b,w in edges:\n m[a].append((b,w))\n m[b].append((a,w))\n def getnb(i):\n return [j for j,w in m[i]]\n lca = LCA(0, getnb)\n def dp(i,prev,c):\n count[i] = c\n for j,w in m[i]:\n if j==prev: continue\n c2 = c.copy()\n c2[w] += 1\n dp(j, i, c2)\n dp(0,0,Counter())\n def query(a,b):\n if a==b: return 0\n p = lca.query(a,b)\n c = count[a]+count[b]-count[p]-count[p]\n return sum(c.values()) - max(c.values())\n return [query(a,b) for a,b in queries]\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Java Solution | java-solution-by-imabhideep-a1zk | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you are familiar with binary jumping, then you can tell it right away, becase there | imabhideep | NORMAL | 2024-04-05T16:38:32.609163+00:00 | 2024-04-05T16:38:32.609196+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you are familiar with binary jumping, then you can tell it right away, becase there are two nodes given, and you need to find the path between the two nodes, and to find the path, you ougth to find the lca of those two nodes. Thereby, lca, means, binary lifting.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nif you see the constraints, then, you will notice, the edge weights are constrained at 26, for which you can take a constant array of that size. The use binary lifting to create a matrix, which contains the frequency of the edge weights in respective paths. Then, similar to how you find, the lca, find out the frequency of edge weights in those paths.\n\nIf you wanna optimize even further, then, instead of using array, use bitwise operator, and xor, it will be faster.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n static ArrayList<Integer> tree[];\n // static int edgeWeight[][][];\n static int edgeWeightLifting[][][];\n static HashMap<ArrayList<Integer>,int[]> edgewt;\n static int depth[]; \n static Tree t;\n static int n;\n public int[] minOperationsQueries(int n1, int[][] edges, int[][] queries) {\n n=n1; \n tree=new ArrayList[n+1];\n // edgeWeight=new int[n][n][27];\n edgewt=new HashMap<>();\n edgeWeightLifting=new int[n][14][27];\n for(int i=0;i<=n;i++)tree[i]=new ArrayList<Integer>();\n for(int i[]:edges){\n tree[i[0]].add(i[1]);\n tree[i[1]].add(i[0]);\n addEdgeWeight(i);\n }\n t=new Tree();\n // t.printBinaryLifting();\n // t.printEdgeLifting();\n int answer[]=new int[queries.length];\n int c=0;\n for(int q[]:queries){\n answer[c++]=getOutput(q);\n }\n return answer;\n }\n static void addEdgeWeight(int i[]){\n // ++edgeWeight[i[0]][i[1]][i[2]];\n // ++edgeWeight[i[1]][i[0]][i[2]];\n ArrayList<Integer> temp=new ArrayList<Integer>();\n temp.add(i[0]);\n temp.add(i[1]);\n if(!edgewt.containsKey(temp)){\n edgewt.put(temp,new int[27]);\n }\n ++edgewt.getOrDefault(temp,new int[27])[i[2]];\n }\n static int getOutput(int q[]){\n int a=q[0];\n int b=q[1];\n if(t.depth[a]<t.depth[b]){\n int temp=a;\n a=b;\n b=temp;\n }\n int dif=t.depth[a]-t.depth[b];\n int level=0;\n int hm[]=t.initialize();\n int hm_a[]=t.initialize();\n int hm_b[]=t.initialize();\n while(dif>0){\n if((dif&1)==1){\n t.add(hm_a,edgeWeightLifting[a][level]);\n a=t.binaryLifting[a][level];\n }\n ++level;\n dif=dif>>1;\n }\n if(a==b){\n t.add(hm,hm_a);\n }\n else{\n // System.out.println(a+" "+b+" "+Arrays.toString(hm_a));\n for(int i=t.HEIGHT-1;i>=0;i--){\n if(t.binaryLifting[a][i]!=t.binaryLifting[b][i]){\n // if(a!=b){\n t.add(hm_a,edgeWeightLifting[a][i]);\n t.add(hm_b,edgeWeightLifting[b][i]);\n a=t.binaryLifting[a][i];\n b=t.binaryLifting[b][i];\n }\n }\n t.add(hm_a,getEdgeWeight(a,t.binaryLifting[a][0]));\n t.add(hm_b,getEdgeWeight(b,t.binaryLifting[b][0]));\n t.add(hm,hm_a);\n t.add(hm,hm_b);\n }\n // System.out.println(q[0]+" "+q[1]+" "+Arrays.toString(hm));\n return getResult(hm);\n }\n static int[] getEdgeWeight(int a, int b){\n // return edgeWeight[a][b];\n ArrayList<Integer> temp1=new ArrayList<Integer>();\n ArrayList<Integer> temp2=new ArrayList<Integer>();\n temp1.add(a);temp1.add(b);\n temp2.add(b);temp2.add(a);\n if(edgewt.containsKey(temp1))return edgewt.get(temp1);\n else return edgewt.get(temp2);\n }\n static int getResult(int arr[]){\n int sum=0,max=0;\n for(int i:arr){\n max=Math.max(max,i);\n sum+=i;\n }\n return sum-max;\n }\n static class Tree extends Solution {\n static int HEIGHT=14;\n static int depth[];\n // static int n=10000;\n static int binaryLifting[][];\n Tree(){\n binaryLifting=new int[n+1][14];\n for(int i[]:binaryLifting)Arrays.fill(i,-1);\n depth=new int[n+1];\n dfs(0,-1);\n }\n static int LCA(int a, int b) {\n if(depth[a]>depth[b]){\n int temp=a;\n a=b;\n b=temp;\n }\n // depth of a is less than depth of b\n b=jump(b,depth[b]-depth[a]);\n if(a==b){\n return a;\n }\n for(int i=HEIGHT-1;i>=0;i--){\n if(binaryLifting[a][i]!=binaryLifting[b][i]){\n a=binaryLifting[a][i];\n b=binaryLifting[b][i];\n }\n }\n return binaryLifting[a][0];\n }\n static int jump(int a, int height){\n int level=0;\n while(height!=0){\n if((height&1)==1){\n a=binaryLifting[a][level];\n }\n level+=1;\n height=height>>1;\n }\n return a;\n }\n static void printBinaryLifting(){\n System.out.println();\n for(int i=0;i<=n;i++){\n System.out.print(i+" : ");\n for(int j=0;j<HEIGHT;j++){\n System.out.print(binaryLifting[i][j]+" ");\n }\n System.out.println();\n }\n }\n static void printEdgeLifting(){\n System.out.println();\n for(int i=0;i<n;i++){\n System.out.print(i+" : ");\n for(int j=0;j<4;j++){\n System.out.print(Arrays.toString(edgeWeightLifting[i][j])+" ");\n }\n System.out.println();\n }\n }\n static int[] initialize(){\n int hm[]=new int[27];\n return hm;\n }\n // static void add(int hm[], int node){\n // int n=edgeWeight[node]==-1?0:1;\n // ++hm[n];\n // }\n static void add(int hm[], int child[]){\n for(int i=0;i<hm.length;i++){\n hm[i]+=child[i];\n }\n }\n static void dfs(int node, int par){\n binaryLifting[node][0]=par;\n if(par!=-1){\n depth[node]=depth[par]+1;\n add(edgeWeightLifting[node][0],getEdgeWeight(node,par));\n }\n for(int level=1;level<HEIGHT;level++){\n if(binaryLifting[node][level-1]==-1)break;\n binaryLifting[node][level]=binaryLifting[binaryLifting[node][level-1]][level-1];\n if(binaryLifting[node][level]==-1)break;\n add(edgeWeightLifting[node][level],edgeWeightLifting[node][level-1]);\n add(edgeWeightLifting[node][level],edgeWeightLifting[binaryLifting[node][level-1]][level-1]);\n }\n for(int childNode:tree[node]){\n if(childNode==par)continue;\n dfs(childNode, node);\n }\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | JAVA 60ms(98%), using LCA | java-60ms98-using-lca-by-meringueee-3pjt | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | meringueee | NORMAL | 2024-03-28T08:14:20.664350+00:00 | 2024-03-28T08:14:20.664376+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n class node{\n int i, v;\n node(int _i, int _v){\n i=_i; v=_v;\n }\n }\n public int[] minOperationsQueries(int n, int[][] es, int[][] qs) {\n List<node>[] con = new List[n];\n for(int i=0; i<n; i++)con[i]=new ArrayList<>();\n\n for(int[] e:es){\n con[e[0]].add(new node(e[1],e[2]));\n con[e[1]].add(new node(e[0],e[2])); \n }\n\n int[][] p = new int[n][15];\n int[] l = new int[n];\n int[][] w = new int[n][27];\n makeP(0, 0, con, p, w, l);\n\n int[] x = new int[qs.length];\n for(int i=0; i<qs.length; i++){\n x[i] = calc(qs[i][0], qs[i][1], p, w, l);\n }\n return x;\n }\n private int calc(int a, int b, int[][] p, int[][] w, int[] l){\n int c = getComPar(a, b, p, l);\n \n int min = Integer.MAX_VALUE;\n for(int i=1; i<=26; i++){\n int tmp = (w[a][0]-w[c][0])+(w[b][0]-w[c][0]) \n - (w[a][i]-w[c][i]) - (w[b][i]-w[c][i]);\n if(min>tmp)min=tmp;\n }\n return min;\n }\n private int getComPar(int a, int b, int[][] p, int[] l){\n if(l[a]<l[b]){\n b = ance(b, p, l[b]-l[a]);\n }else if(l[a]>l[b]){\n a = ance(a, p, l[a]-l[b]);\n }\n int u;\n while(a!=b){\n if(p[a][0]==p[b][0])return p[a][0];\n for(u=0; p[a][u+1]!=p[b][u+1];u++);\n a=p[a][u]; b=p[b][u];\n }\n return a;\n }\n private int ance(int a, int[][] p, int t){\n for(int i=0; t>0; i++){\n if(t%2==1)a = p[a][i];\n t/=2;\n }\n return a;\n }\n private void makeP(int c, int a, List<node>[] con, int[][] p, int[][] w, int[] l){\n p[c][0]=a;\n l[c]=l[a]+1;\n for(int i=0; p[c][i]!=0; i++)p[c][i+1]=p[p[c][i]][i];\n for(node b:con[c]){\n if(b.i == a)continue;\n for(int i=0; i<=26; i++)w[b.i][i]=w[c][i];\n w[b.i][b.v]++; w[b.i][0]++;\n makeP(b.i, c, con, p, w, l);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Easy Clear Solution :) | easy-clear-solution-by-user20222-wrvp | \n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>>dp;\n void dfs1(vector<vector<pair<int,int>>>&tree,int node,int p,vector<int>&freq){\n | user20222 | NORMAL | 2024-03-28T07:31:11.912336+00:00 | 2024-03-28T07:31:11.912360+00:00 | 4 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>dp;\n void dfs1(vector<vector<pair<int,int>>>&tree,int node,int p,vector<int>&freq){\n dp[node]=freq;\n for(auto&ch:tree[node]){\n if(ch.first!=p){\n freq[ch.second]++;\n dfs1(tree,ch.first,node,freq);\n freq[ch.second]--;\n }\n }\n }\n \n \n vector<vector<int>>lift;\n void blift(vector<vector<pair<int,int>>>&tree,int node,int p){\n if(p!=-1){\n lift[node].push_back(p);\n int pindex = 0;\n while(1){\n int pnode = lift[node].back();\n if(lift[pnode].size()>pindex){\n lift[node].push_back(lift[pnode][pindex++]);\n }\n else break;\n }\n }\n for(auto&ch:tree[node]){\n if(ch.first!=p){\n blift(tree,ch.first,node);\n }\n }\n }\n \n \n vector<int>level;\n void flevel(vector<vector<pair<int,int>>>&tree,int node,int p,int l){\n level[node] = l;\n for(auto&ch:tree[node]){\n if(ch.first!=p){\n flevel(tree,ch.first,node,l+1);\n }\n }\n }\n \n \n \n int leveling(int node,int diff){\n while(diff){\n int x = log2(diff); \n node = lift[node][x];\n diff-=(1<<x);\n }\n return node;\n }\n int LCA(vector<vector<pair<int,int>>>&tree,int a,int b){\n int levela = level[a];\n int levelb = level[b];\n \n if(levela>levelb){\n a = leveling(a,levela-levelb);\n }\n else b = leveling(b,levelb-levela);\n \n if(a==b)return a; \n while(1){\n bool flag = 0;\n for(int i=0;i<lift[a].size();i++){\n if(lift[a][i]==lift[b][i]){\n if(i==0)return lift[a][i];\n a = lift[a][i-1];\n b = lift[b][i-1];\n flag = 1;\n break;\n }\n }\n if(!flag){\n a = lift[a].back();\n b = lift[b].back();\n }\n }\n return -1;\n }\n \n \n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& q) {\n vector<vector<pair<int,int>>>tree(n);\n for(auto&it:edges){\n tree[it[0]].push_back({it[1],it[2]-1});\n tree[it[1]].push_back({it[0],it[2]-1});\n }\n \n \n dp.assign(n,vector<int>(26,0));\n vector<int>temp(26,0);\n dfs1(tree,0,-1,temp);\n \n \n lift.clear();\n lift.resize(n);\n blift(tree,0,-1);\n \n level.assign(n,-1);\n flevel(tree,0,-1,0);\n \n \n vector<int>ans;\n for(auto&it:q){\n int a = it[0];\n int b = it[1];\n int c = LCA(tree,a,b); \n vector<int>freq = dp[a]; \n for(int i=0;i<26;i++){\n freq[i]+=dp[b][i];\n freq[i]-=2*dp[c][i];\n } \n int totalEdges = accumulate(freq.begin(),freq.end(),0);\n int maxr = *max_element(freq.begin(),freq.end());\n ans.push_back(totalEdges-maxr);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Java Clean Code With Comment - Binary Lifting | java-clean-code-with-comment-binary-lift-0oes | Intuition\nSince it\'s a tree (not necessarily binary), every path from a to b is unique, plus the magnitude of query indicates it\'s better to precompute parti | ericwangirvine | NORMAL | 2024-02-26T19:04:11.831559+00:00 | 2024-02-28T12:30:05.716920+00:00 | 21 | false | # Intuition\nSince it\'s a tree (not necessarily binary), every path from a to b is unique, plus the magnitude of query indicates it\'s better to precompute partial results.\n\n# Approach\n- Transform undirected graph to a tree (directed graph) and precompute every weight frequency of path starting from root\n- Calculate LCA through binary lifting, with the help of precomputed dp matrix\n\nOriginally I added the logic of minimum height tree (topological sort) to find the best root but since we are using binary lifting the perf gain from it is not that significant.\n\n# Complexity\n- Time complexity:\n$$O(n * m) + O(q * log(n))$$ or\n$$O(n * log(n)) + O(q * log(n))$$ since $$m$$ is $$log(n)$$\n\n- Space complexity:\n$$O(n * m)$$\n\n# Code\n```java []\nclass Solution {\n // n : number of nodes/edges\n // m : 2nd dimension from binary lifting dp matrix\n // q : number of queries\n // 26 : maximum weight\n\n class Node {\n int id;\n Map<Integer, Integer> neighbors;\n\n public Node(int id) {\n this.id = id;\n this.neighbors = new HashMap<>();\n }\n }\n\n private Node[] nodes;\n private int[][] weight, dp;\n private int[] depth;\n private int m;\n private final int WEIGHT_LIMIT = 26, ROOT_ID = 0;\n\n // O(n * (m + 26)) + O(26 * q * log(n))\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n init(n, edges);\n buildTree(ROOT_ID, -1);\n int[] result = new int[queries.length];\n\n for (int i = 0; i < result.length; i++) { // O(26 * q * log(n))\n int a = queries[i][0], b = queries[i][1], c = lca(a, b);\n int pathLen = depth[a] + depth[b] - 2 * depth[c], maxFreq = 0;\n for (int w = 1; w <= WEIGHT_LIMIT; w++) {\n int freq = weight[a][w] + weight[b][w] - 2 * weight[c][w];\n maxFreq = Math.max(maxFreq, freq);\n }\n result[i] = pathLen - maxFreq;\n }\n\n return result;\n }\n\n // O(log(n)) even for skewed tree\n private int lca(int a, int b) {\n if (depth[a] < depth[b]) return lca(b, a);\n int diff = depth[a] - depth[b];\n for (int j = m - 1; j >= 0; j--) {\n if ((diff & (1 << j)) > 0) {\n a = dp[a][j];\n }\n }\n if (a == b) return a;\n for (int j = m - 1; j >= 0; j--) {\n if (dp[a][j] != dp[b][j]) {\n a = dp[a][j];\n b = dp[b][j];\n }\n }\n return dp[a][0];\n }\n \n // O(n * (m + 26))\n // transform the undirected graph to a tree\n private void buildTree(int rootId, int parentId) {\n for (int childId: nodes[rootId].neighbors.keySet()) {\n // skip parent node to keep the graph directed\n if (childId == parentId) continue;\n\n // populate depth matrix\n depth[childId] = depth[rootId] + 1;\n \n // binary lifting\n for (int j = 0; j < m; j++) {\n if (j == 0) dp[childId][j] = rootId;\n else dp[childId][j] = dp[childId][j - 1] == -1 ? -1 : dp[dp[childId][j - 1]][j - 1];\n }\n\n // update weight matrix\n int newWeight = nodes[rootId].neighbors.get(childId);\n for (int w = 1; w <= WEIGHT_LIMIT; w++) {\n weight[childId][w] += weight[rootId][w];\n if (w == newWeight) weight[childId][w]++;\n }\n\n buildTree(childId, rootId);\n }\n }\n\n // O(n)\n private void init(int n, int[][] edges) {\n this.depth = new int[n];\n this.weight = new int[n][WEIGHT_LIMIT + 1];\n this.m = (int)(Math.log(n) / Math.log(2)) + 1;\n this.dp = new int[n][m];\n Arrays.fill(dp[ROOT_ID], -1);\n \n this.nodes = new Node[n];\n for (int i = 0; i < n; i++) nodes[i] = new Node(i);\n \n for (int[] edge: edges) {\n int from = edge[0], to = edge[1], weight = edge[2];\n nodes[from].neighbors.put(to, weight);\n nodes[to].neighbors.put(from, weight);\n }\n }\n}\n``` | 0 | 0 | ['Bit Manipulation', 'Tree', 'Graph', 'Topological Sort', 'Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | binary lifting | binary-lifting-by-parkcloud-lyeg | Intuition\nthink of path of node a to b is terms of path of root to a and path of root to b minus 2 * path of root to lca(a,b).\n\n# Approach\n Describe your ap | parkCloud | NORMAL | 2023-12-29T02:17:06.043357+00:00 | 2023-12-29T02:17:06.043374+00:00 | 3 | false | # Intuition\nthink of path of node a to b is terms of path of root to a and path of root to b minus 2 * path of root to lca(a,b).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar minOperationsQueries = function (n, edges, queries) {\n let LOG = 20\n let freq = Array(n).fill(0).map((row) => Array(27).fill(0)) // freq[node][w]\n let up = Array(n).fill(0).map((row) => Array(LOG).fill(-1))\n let depth = Array(n).fill(0)\n let graph = new Map()\n for (const [at, to, w] of edges) {\n if (!graph.has(at)) {\n graph.set(at, [])\n }\n if (!graph.has(to)) {\n graph.set(to, [])\n }\n graph.get(at).push([to, w])\n graph.get(to).push([at, w])\n }\n function dfs(at, parent, w, dep) {\n up[at][0] = parent\n depth[at] = dep\n for (let i = 1; i < LOG; i++) {\n let p = up[at][i - 1]\n if (p == -1) break\n up[at][i] = up[p][i - 1]\n }\n if (parent !== -1) {\n freq[at] = [...freq[parent]]\n freq[at][w] += 1\n }\n for (const [to, w] of graph.get(at) || []) {\n if (to !== parent) {\n dfs(to, at, w, dep + 1)\n }\n }\n }\n dfs(0, -1, 0, 0)\n function lca(u, v) {\n // assure depth of node u is greater\n if (depth[u] < depth[v]) {\n return lca(v, u)\n }\n // put u and v at the same level\n let diff = depth[u] - depth[v]\n for (let i = LOG; i > -1; i--) {\n if (diff & (1 << i)) {\n u = up[u][i]\n }\n }\n if (u == v) return u\n for (let i = LOG; i > -1; i--) {\n if (up[u][i] !== up[v][i]) {\n u = up[u][i]\n v = up[v][i]\n }\n }\n return up[u][0]\n\n }\n let m = queries.length\n let ans = Array(m).fill(0)\n for (let i = 0; i < m; i++) {\n let [u, v] = queries[i]\n let p = lca(u, v)\n let total = 0\n let max = 0\n for (let i = 0; i < 27; i++) {\n let res = freq[u][i] + freq[v][i] - 2 * freq[p][i]\n total += res\n max = Math.max(max, res)\n }\n ans[i] = total - max\n\n }\n return ans\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | ✅ JAVA | Binary Lifting🔥🔥 | LCA | 🚀🚀 Simple🔥 Clean Code | Easy to Understand✅✅ | java-binary-lifting-lca-simple-clean-cod-k6gp | Intuition\n Describe your first thoughts on how to solve this problem. \nDFS + LCA + HashMap for storing freq of elements\n# Approach\n Describe your approach t | sanjitpro | NORMAL | 2023-12-22T19:32:28.061862+00:00 | 2023-12-22T19:32:28.061890+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDFS + LCA + HashMap for storing freq of elements\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n List<Integer> up[];\n List<int[]> g[];\n List<HashMap<Integer,Integer>> freq;\n int tin[];\n int tout[];\n int timer;\n int ans[];\n int height[];\n int l = 20;\n\n void dfs(int root, int par, int h) {\n if (tin[root]>0) return;\n timer++;\n tin[root] = timer;\n height[root]=h;\n up[root].set(0, par);\n for (int i=1;i<l;++i)\n up[root].set(i, up[up[root].get(i-1)].get(i-1));\n for (int e[]:g[root]) {\n if (e[0]==par) continue;\n HashMap<Integer, Integer> hm = new HashMap<>();\n hm.putAll(freq.get(root));\n hm.put(e[1], hm.getOrDefault(e[1], 0)+1);\n freq.set(e[0], hm);\n dfs(e[0], root, h+1);\n }\n tout[root] = timer;\n }\n\n boolean isAncestor(int u, int v) {\n return (tin[u]<=tin[v] && tout[u]>=tout[v]);\n }\n\n int lca(int u, int v) {\n if (isAncestor(u, v))\n return u;\n if (isAncestor(v, u))\n return v;\n for (int i=l-1;i>=0;--i) {\n if (!isAncestor(up[u].get(i), v))\n u = up[u].get(i);\n }\n return up[u].get(0);\n }\n\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n up = new ArrayList[n];\n g = new ArrayList[n];\n freq = new ArrayList<>();\n for (int i=0;i<n;++i) {\n g[i] = new ArrayList<>();\n up[i] = new ArrayList<>();\n freq.add(new HashMap());\n for (int j=0;j<l;++j)\n up[i].add(0);\n }\n timer=0;\n tin = new int[n];\n tout = new int[n];\n height = new int[n];\n for (int e[] : edges) {\n g[e[0]].add(new int[]{e[1], e[2]});\n g[e[1]].add(new int[]{e[0], e[2]});\n }\n for (int i=0;i<n;++i)\n dfs(i, i, 1);\n int q = queries.length;\n ans = new int[q];\n for (int i=0;i<q;++i) {\n int u = queries[i][0];\n int v = queries[i][1];\n int lc = lca(u, v);\n // System.out.println(u + " : " + v + " : " + lc);\n // System.out.println(freq.get(u));\n // System.out.println(freq.get(v));\n // System.out.println(freq.get(lc));\n HashMap<Integer, Integer> hm = new HashMap<>();\n hm.putAll(freq.get(u));\n for (Map.Entry<Integer, Integer> e:freq.get(v).entrySet()) {\n hm.put(e.getKey(), hm.getOrDefault(e.getKey(), 0)+e.getValue());\n }\n for (Map.Entry<Integer, Integer> e:freq.get(lc).entrySet()) {\n Integer kk = e.getKey();\n Integer vv = e.getValue();\n hm.put(kk, hm.get(kk)-2*vv);\n }\n int mx=0;\n for (int val : hm.values()) {\n mx = Math.max(mx, val);\n }\n ans[i]=(height[u]+height[v]-2*height[lc])-mx;\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Linear Time C++ with Tarjan's Algorithm | linear-time-c-with-tarjans-algorithm-by-sar6g | Intuition\n Describe your first thoughts on how to solve this problem. \nUse Tarjan\'s algorithm to calculate the lca for each query (u, v). Compute the depths | user___ | NORMAL | 2023-12-12T08:26:51.762195+00:00 | 2023-12-12T08:26:51.762217+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Tarjan\'s algorithm to calculate the $$lca$$ for each query $$(u, v)$$. Compute the depths and edge counts for every node first so that each query $$(u, v)$$ can be answered in constant time given $$lca(u, v)$$. \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n int m = queries.size();\n\n adjList.resize(n, vector<pair<int, int>>());\n\n for (vector<int>& edge : edges) {\n adjList[edge[0]].push_back({edge[1], edge[2]});\n adjList[edge[1]].push_back({edge[0], edge[2]});\n }\n\n count.resize(27, vector<int>(n, 0));\n\n depth.resize(n, 0);\n\n dfsCount(0, -1);\n\n p.resize(n, 0);\n for (int i = 0; i < n; i++) {\n p[i] = i;\n }\n r.resize(n, 0);\n\n queryPair.resize(n, vector<int>());\n\n for (int i = 0; i < m; i++) {\n vector<int>& query = queries[i];\n queryPair[query[0]].push_back(i);\n queryPair[query[1]].push_back(i);\n }\n\n visited.resize(n, 0);\n\n rep.resize(n, 0);\n\n ans.resize(m, 0);\n\n dfsTarjan(0, -1, queries);\n\n return ans;\n }\n\n void dfsCount(int root, int parent) {\n for (pair<int, int>& edge : adjList[root]) {\n int child = edge.first;\n int w = edge.second;\n if (child != parent) {\n for (int i = 1; i <= 26; i++) {\n count[i][child] = (w == i) + count[i][root];\n }\n depth[child] = 1 + depth[root];\n dfsCount(child, root);\n }\n }\n }\n\n void dfsTarjan(int root, int parent, vector<vector<int>>& queries) {\n visited[root] = 1;\n rep[root] = root;\n\n for (pair<int, int> edge : adjList[root]) {\n int child = edge.first;\n int w = edge.second;\n if (child != parent) {\n dfsTarjan(child, root, queries);\n unionFind(child, root);\n rep[find(root)] = root;\n }\n }\n\n for (int& i : queryPair[root]) {\n int u = queries[i][0] == root ? queries[i][1] : queries[i][0];\n if (visited[u]) {\n int lca = rep[find(u)];\n int num = depth[u] + depth[root] - 2 * depth[lca];\n int maxEdge = 0;\n for (int j = 1; j <= 26; j++) {\n maxEdge = max(maxEdge, count[j][u] + count[j][root] - 2 * count[j][lca]);\n }\n ans[i] = num - maxEdge;\n }\n }\n }\n\n int find(int x) {\n if (p[x] == x) {\n return x;\n } else {\n int parentVal = find(p[x]);\n // path compression\n p[x] = parentVal;\n return parentVal;\n }\n }\n\n bool unionFind(int x, int y) {\n int parentX = find(x);\n int parentY = find(y);\n\n int rankX = r[parentX];\n int rankY = r[parentY];\n // union by rank\n if (rankX <= rankY) {\n p[parentX] = parentY;\n if (rankX == rankY) {\n r[parentY]++;\n }\n } else if (rankY < rankX) {\n p[parentY] = parentX;\n }\n\n return parentX == parentY;\n }\n\nprivate:\n vector<vector<pair<int, int>>> adjList;\n vector<vector<int>> count;\n vector<int> p;\n vector<int> r;\n vector<vector<int>> queryPair;\n vector<int> rep;\n vector<int> visited;\n vector<int> ans;\n vector<int> depth;\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++. LCA. Counters on vertices. Clean af | c-lca-counters-on-vertices-clean-af-by-4-nm0x | \n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define F first\n#define S second\n#define forn(i, n) for(int i = 0; i < n; ++i)\n#define forbn(i, b, n) f | 404akhan | NORMAL | 2023-11-09T10:21:15.487314+00:00 | 2023-11-09T10:21:15.487347+00:00 | 4 | false | ```\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define F first\n#define S second\n#define forn(i, n) for(int i = 0; i < n; ++i)\n#define forbn(i, b, n) for(int i = b; i < n; ++i)\n#define sz(v) (int)v.size()\n#define pb push_back\n\ntypedef pair<int, int> ii;\ntypedef vector<int> vi;\ntypedef vector<ii> vii;\n\ntemplate <class T> inline void mineq(T &a, T b) { a = min(a, b); }\ntemplate <class T> inline void maxeq(T &a, T b) { a = max(a, b); }\n\n\nclass Solution {\npublic:\n\tstatic const int N = 10010;\n vii gr[N];\n vi ct[N];\n int timer = -1;\n int tin[N], tout[N];\n int pr[16][N];\n int depth[N];\n\n\n void dfs(int node, int par = 0, int w = -1, int dep = 0) {\n \ttin[node] = ++timer;\n \tpr[0][node] = par;\n \tdepth[node] = dep;\n\n \tforn(i, 26) {\n \t\tct[node][i] = ct[par][i];\n \t\tif(i == w)\n \t\t\tct[node][i] += 1;\n \t}\n\n \tfor(ii to: gr[node]) {\n \t\tif(to.F == par)\n \t\t\tcontinue;\n \t\tdfs(to.F, node, to.S, dep + 1);\n \t}\n \ttout[node] = timer;\n }\n\n\n bool is_par(int a, int b) {\n \tif(a == 0)\n \t\treturn true;\n \treturn tin[a] <= tin[b] && tout[b] <= tout[a];\n }\n\n\n int lca(int a, int b) {\n \tif(is_par(a, b))\n \t\treturn a;\n \tif(is_par(b, a))\n \t\treturn b;\n\n \tfor(int w = 15; w >= 0; w--) {\n \t\tif(!is_par(pr[w][b], a))\n \t\t\tb = pr[w][b];\n \t}\n \treturn pr[0][b];\n }\n\n\n\tvector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n\t\tforn(i, n - 1) {\n\t\t\tint u = edges[i][0] + 1;\n\t\t\tint v = edges[i][1] + 1;\n\t\t\tint w = edges[i][2] - 1;\n\n\t\t\tgr[u].pb({v, w});\n\t\t\tgr[v].pb({u, w});\n\t\t}\n\t\tforn(i, n + 1) {\n\t\t\tct[i].resize(26);\n\t\t}\n\n\t\tdfs(1);\n\t\tforbn(w, 1, 16) {\n\t\t\tforbn(i, 1, n + 1) {\n\t\t\t\tint par = pr[w - 1][i];\n\t\t\t\tpr[w][i] = pr[w - 1][par];\n\t\t\t}\n\t\t}\n\n\t\tvi ans;\n\t\tforn(q, sz(queries)) {\n\t\t\tint u = queries[q][0] + 1;\n\t\t\tint v = queries[q][1] + 1;\n\t\t\tint p = lca(u, v);\n\t\t\tint mx = 0;\n\t\t\tint pl = depth[u] + depth[v] - 2 * depth[p];\n\n\t\t\tforn(i, 26) {\n\t\t\t\tmaxeq(mx, ct[u][i] + ct[v][i] - 2 * ct[p][i]);\n\t\t\t}\n\n\t\t\tans.pb(pl - mx);\n\t\t}\n\t\treturn ans;\n }\n};\n\n``` | 0 | 0 | [] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | My Lengthy but easy to understand java solution :)) | my-lengthy-but-easy-to-understand-java-s-u4w2 | Code\n\nclass Solution {\n public static int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n // STEP 0 - Populate the parent & dept | Bhavyaa_Arora_08 | NORMAL | 2023-10-22T06:51:21.758412+00:00 | 2023-10-22T06:51:21.758434+00:00 | 13 | false | # Code\n```\nclass Solution {\n public static int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n // STEP 0 - Populate the parent & depth array & freq[node][wt]\n ArrayList<int[]>[] adj = new ArrayList[n];\n for (int i = 0; i < n; i++)\n adj[i] = new ArrayList<>();\n for (int[] edge : edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n adj[u].add(new int[] { v, w });\n adj[v].add(new int[] { u, w });\n }\n freq = new int[n][26 + 1];\n depth = new int[n];\n parent = new int[n];\n dfs(0, -1, 0, adj);\n\n // STEP 1 - Pre processing - binary lifting - for (ancestors, depth of node)\n preProcess(n);\n\n // STEP 2 - Find answer to each query\n int[] ans = new int[queries.length];\n for (int i = 0; i < ans.length; i++) {\n int n1 = queries[i][0], n2 = queries[i][1];\n int lca = getLCA(n1, n2);\n int total_edges = depth[n1] + depth[n2] - (2 * depth[lca]);\n int mf = 0;\n for (int j = 0; j <= 26; j++) \n mf = Math.max(mf, freq[n1][j] + freq[n2][j] - (2 * freq[lca][j]));\n ans[i] = total_edges - mf;\n }\n\n return ans;\n }\n\n public static void dfs(int u, int par, int d, ArrayList<int[]>[] adj) {\n depth[u] = Math.max(depth[u], d);\n parent[u] = par;\n\n for (int[] v : adj[u]) {\n if (v[0] == par) continue;\n freq[v[0]][v[1]]++;\n for (int j = 0; j <= 26; ++j)\n freq[v[0]][j] += freq[u][j];\n dfs(v[0], u, d + 1, adj);\n }\n }\n\n public static int getLCA(int n1, int n2) {\n int depth1 = depth[n1];\n int depth2 = depth[n2];\n if (depth1 > depth2) {\n int temp = n1;\n n1 = n2;\n n2 = temp;\n }\n\n // Adjust n2 to same depth as n1\n int k = Math.abs(depth2 - depth1); // or go to moveByth ancestor\n int level = 0;\n while (k > 0) {\n if ((k & 1) == 1) {\n if (n2 == -1) break;\n n2 = up[n2][level];\n }\n k >>= 1;\n level++;\n }\n\n // Move both of them one by one until we get same nodes\n while (n1 != n2 && n1 != -1 && n2 != -1) {\n n1 = parent[n1];\n n2 = parent[n2];\n }\n\n return n1;\n }\n\n static int[][] freq;\n static int[] parent;\n static int[] depth;\n static int[][] up;\n static int LOG;\n\n public static void preProcess(int n) {\n LOG = (int) (Math.log(n) / Math.log(2)) + 1;\n up = new int[n][LOG + 1];\n for (int i = 0; i < n; i++)\n Arrays.fill(up[i], -1);\n for (int j = 0; j < LOG; j++) {\n for (int i = 0; i < n; i++) {\n if (j == 0)\n up[i][j] = parent[i];\n else {\n if (up[i][j - 1] == -1)\n up[i][j] = -1;\n else\n up[i][j] = up[up[i][j - 1]][j - 1];\n }\n }\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA | lca-by-_kitish-q2by | Code\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vecto | _kitish | NORMAL | 2023-10-19T10:56:14.836963+00:00 | 2023-10-19T10:56:14.836991+00:00 | 6 | false | # Code\n```\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<pair<int,int>>> g(n);\n vector<int> lvl(n);\n map<int,array<int,27>> freq;\n vector<vector<int>> dp(n,vector<int>(31));\n\n for(auto e: edges){\n int u = e[0], v = e[1], w = e[2];\n g[u].push_back({v,w});\n g[v].push_back({u,w});\n }\n\n auto dfs = [&](auto&&dfs,int u,int p,int l) -> void {\n lvl[u] = l;\n dp[u][0] = p;\n for(int i=1; i<31; ++i){\n if(dp[u][i-1] != -1)\n dp[u][i] = dp[dp[u][i-1]][i-1];\n else\n dp[u][i] = -1;\n }\n for(auto [v,w]: g[u]){\n if(v != p){\n freq[v] = freq[u];\n freq[v][w]++;\n dfs(dfs,v,u,l+1);\n }\n }\n };\n\n auto liftnode = [&](int u,int k) -> int {\n for(int i=0; i<31; ++i){\n if(u == -1 || k == 0) break;\n if((k>>i)&1){\n u = dp[u][i];\n k -= (1<<i);\n }\n }\n return u;\n };\n\n auto LCA = [&](int u,int v) -> int {\n if(lvl[u] < lvl[v]) swap(u,v);\n u = liftnode(u,lvl[u]-lvl[v]);\n\n if(u == v) return u;\n\n for(int i=30; i>=0; --i){\n if(dp[u][i] != dp[v][i]){\n u = dp[u][i];\n v = dp[v][i];\n }\n }\n return liftnode(u,1);\n };\n\n dfs(dfs,0,-1,0);\n \n vector<int> ans;\n\n for(auto q: queries){\n int u = q[0], v = q[1];\n int lca = LCA(u,v);\n auto a = freq[u], b = freq[v], c = freq[lca];\n\n for(int i=0; i<27; ++i){\n a[i] = a[i] + b[i] - (2 * c[i]);\n }\n int sum = 0, mx = -1e9;\n for(int e: a){\n sum += e;\n mx = max(mx,e);\n }\n ans.push_back(sum-mx);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Tree', 'Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Just a runnable solution | just-a-runnable-solution-by-ssrlive-vgyd | \n\nimpl Solution {\n fn dfs(u: usize, p: usize, memo: &mut Vec<Vec<i32>>, lev: &mut Vec<i32>, log: usize, adj: &Vec<Vec<(usize, i32)>>) {\n memo[u][0 | ssrlive | NORMAL | 2023-10-18T08:25:46.263854+00:00 | 2023-10-18T08:25:46.263870+00:00 | 7 | false | \n```\nimpl Solution {\n fn dfs(u: usize, p: usize, memo: &mut Vec<Vec<i32>>, lev: &mut Vec<i32>, log: usize, adj: &Vec<Vec<(usize, i32)>>) {\n memo[u][0] = p as i32;\n for i in 1..=log {\n memo[u][i] = memo[memo[u][i - 1] as usize][i - 1];\n }\n for x in adj[u].iter() {\n let v = x.0;\n if v != p {\n lev[v] = lev[u] + 1;\n Solution::dfs(v, u, memo, lev, log, adj);\n }\n }\n }\n\n fn lca(u: usize, v: usize, log: usize, lev: &[i32], memo: &[Vec<i32>]) -> usize {\n let mut u = u;\n let mut v = v;\n if lev[u] < lev[v] {\n std::mem::swap(&mut u, &mut v);\n }\n println!("log: {}", log);\n for i in (0..=log).rev() {\n if (lev[u] as i64 - (1_i64 << i)) >= lev[v] as i64 {\n u = memo[u][i] as usize;\n }\n }\n if u == v {\n return u;\n }\n for i in (0..=log).rev() {\n if memo[u][i] != memo[v][i] {\n u = memo[u][i] as usize;\n v = memo[v][i] as usize;\n }\n }\n memo[u][0] as usize\n }\n\n fn get_count(n: usize, par: usize, adj: &Vec<Vec<(usize, i32)>>, count: &mut Vec<Vec<i32>>) {\n for i in 0..27 {\n count[n][i] += count[par][i];\n }\n for x in adj[n].iter() {\n if x.0 != par {\n count[x.0][x.1 as usize] += 1;\n Solution::get_count(x.0, n, adj, count);\n }\n }\n }\n\n pub fn min_operations_queries(n: i32, edges: Vec<Vec<i32>>, queries: Vec<Vec<i32>>) -> Vec<i32> {\n let n = n as usize;\n let mut count = vec![vec![0; 27]; n];\n let mut adj = vec![vec![]; n];\n for x in edges.iter() {\n adj[x[0] as usize].push((x[1] as usize, x[2]));\n adj[x[1] as usize].push((x[0] as usize, x[2]));\n }\n Solution::get_count(0, 0, &adj, &mut count);\n\n let log = 32;\n let mut memo = vec![vec![-1; log + 1]; n + 1];\n let mut lev = vec![0; n + 1];\n Solution::dfs(0, 0, &mut memo, &mut lev, log, &adj);\n let mut ans = vec![];\n for x in queries.iter() {\n let l = Solution::lca(x[0] as usize, x[1] as usize, log, &lev, &memo);\n let mut tot = 0;\n let mut mx = 0;\n for i in 0..27 {\n let cur = count[x[0] as usize][i] + count[x[1] as usize][i] - 2 * count[l][i];\n tot += cur;\n mx = mx.max(cur);\n }\n ans.push(tot - mx);\n }\n ans\n }\n}\n\n``` | 0 | 0 | ['Rust'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Python solution using anchor point in O(log(n) x m) | python-solution-using-anchor-point-in-ol-zk9s | Intuition:\nA straightforward approach to this problem involves iterating over each query and employing a BFS or a related traversal algorithm to discern the pa | andrei_bis | NORMAL | 2023-10-12T18:21:43.428815+00:00 | 2023-10-12T18:21:43.428833+00:00 | 12 | false | ## **Intuition:**\nA straightforward approach to this problem involves iterating over each query and employing a BFS or a related traversal algorithm to discern the path between the queried nodes. While traversing this path, we can maintain an `weight_vector` array to record the occurrence of each weight. \n\nThe formula to deduce the result becomes: \n```\nresult = total number of distinct weights on the path - the weight that appears most frequently\n```\nWhich translates to:\n```python\nresult = sum(weight_vector) - max(weight_vector)\n```\nFor instance, assume there are only 4 distinct weights and our path comprises an edge with weight 3 and another with weight 4. The `weight_vector` array manifests as: `[0, 0, 1, 1]`. Hence, the computed result is: `2 - 1 = 1`, meaning we just modify one edge to match the other\'s weight.\n\nGiven its O(n*m) complexity, this brute force approach may falter in cases with higher constraints. An enhancement involves designating an anchor, like node 0, and computing the `weight_vector` from node 0 to all other nodes, achievable recursively in O(n). To find the path from node A to B, one can ingeniously combine the pre-computed paths from 0 to A and 0 to B.\n\n\n\n## **Approach:**\n\nWhat we need is the `weight_vector` between A and B, and what we have is the `weight_vector` between 0 and all nodes in the graph. How to get the first from the second ?\n\nTo compute the `weight_vector` between nodes A and B, we leverage the pre-calculated `weight_vector` from node 0 to all other nodes. The challenge lies in accurately deriving the path between nodes A and B.\n\nLet\'s consider two scenarios for the path from A to B:\n1. **Node 0 is in the path (Scenario A)**:\n - Node 0 lies between nodes A and B. In this case, we can sum the `weight_vector` from node 0 to A and from node 0 to B. This method yields the total weights from A to B, bypassing the need for subtraction or further refinement.\n\n2. **Node 0 is not in the path (Scenario B)**:\n - Here, node 0 isn\u2019t an intermediary between nodes A and B. Directly summing `weight_vector` in this case might lead to counting some edges twice. To mitigate this, we need to identify the first common node (let\u2019s call it `C`) in the paths from 0 to A and from 0 to B. By subtracting the weights from 0 to C, we correct the over-counting issue.\n\nThis leads to 2 different formulas:\nScenario A : \n```python\nweight_vector_A_to_B = weight_vectors[A] + weight_vectors[B]\n```\nScenario B : \n```python\nweight_vector_A_to_B = weight_vectors[A] + weight_vectors[B] - 2 * weight_vectors[C]\n```\n\n\nTo differentiate between these two scenarios:\n- For node 0 to be considered an intermediary, it should act as a bifurcation point, meaning it should connect to more than one edge.\n- In case of a bifurcation at node 0, choosing different edges to reach A or B indicates that node 0 is part of the path.\n\nFor Scenario B, we actually have 2 distinct cases for the common node (`C`) :\n- `C` can be either node A or B themselves when the path from 0 is linear, meaning there are no bifurcations or at each bifuraction we make the same decision.\n- Recognizing `C` as the bifurcation point where diverging decisions were made in reaching nodes A and B, this is where the path branched when going from 0 to A and from 0 to B.\n\nBy storing the encountered bifurcation points and the corresponding decisions made, we can efficiently determine the closest common node, allowing for a precise calculation of the `weight_vector` between nodes A and B.\n\n\n# Complexity\n\n- **Time complexity:**\n - Here we iterate over each query. For each query, in the worst case, we need to consider all possible bifurcation points to find the nature of the path from A to B.\n - How many bifurcation points can there be? For there to be a bifurcation point, the node needs to have at least 3 outgoing edges, or 2 if the node is 0 (which is our anchor point).\n - So the maximum number of bifurcation points is \\(O(log n)\\).\n - Thus, the total time complexity is \\(O(m log(n))\\), which is enough for this exercise.\n\n- **Space complexity:**\n - Here we store an array of size 27 (to account for the weights), leading to a space complexity of \\(O(n 27)\\), simplified to \\(O(n)\\), where \\(n\\) is the number of nodes.\n - The 27 represents the weights from 1 to 26 (inclusive).\n\n\n\n# Code\n```\nclass Solution:\n def _explore_graph(self, graph, start, parent=None):\n """Explore the graph recursively to calculate summary weights and bifurcation nodes."""\n for e in graph[start]:\n result = [0] * 27 # Initializing a result list to store weights\n \n # Skipping the parent or the node itself\n if e[0] == start or e[0] == parent:\n continue\n \n bif_nodes = self.bifurcation_nodes[start].copy()\n # Handling bifurcation nodes, storing the direction taken at the bifurcation\n if len(graph[start]) > 2 or (start == 0 and len(graph[0]) > 1):\n bif_nodes[start] = e[0]\n \n self.bifurcation_nodes[e[0]] = bif_nodes\n result[e[1]] += 1 # Increment the weight\n \n # Add the weights from the parent node\n if parent is not None:\n result = [result[i] + self.weight_summary[start][i] for i in range(27)]\n \n self.weight_summary[e[0]] = result[:]\n # Recursive call to explore the next nodes\n self._explore_graph(graph, e[0], start)\n\n def minOperationsQueries(self, n: int, edges: list[list[int]], queries: list[list[int]]) -> list[int]:\n """Main function to answer the queries based on the preprocessed graph."""\n \n result = [0] * len(queries) # Storing the answers for each query\n graph = [[] for _ in range(n)] # Initializing the graph\n \n self.weight_summary = [[0] * 27 for _ in range(n)] # Summary of weights for each node\n self.bifurcation_nodes = [dict() for _ in range(n)] # Nodes where paths bifurcate\n \n # Building the graph from the edges\n for e in edges:\n graph[e[0]].append([e[1], e[2]])\n graph[e[1]].append([e[0], e[2]])\n \n self._explore_graph(graph, 0)\n \n for i, q in enumerate(queries):\n start, end = q\n \n if start == end:\n continue\n \n # Combining weights from start and end nodes\n weights = [self.weight_summary[start][j] + self.weight_summary[end][j] for j in range(27)]\n \n # Finding common bifurcation nodes\n bif_node_start = self.bifurcation_nodes[start]\n bif_node_end = self.bifurcation_nodes[end]\n common_nodes = set(bif_node_start.keys()).intersection(set(bif_node_end.keys()))\n \n # Identifying different choices made at bifurcation nodes\n biff_nodes = [cn for cn in common_nodes if bif_node_start[cn] != bif_node_end[cn]]\n biff_node = biff_nodes[0] if biff_nodes else None\n \n # Handling different cases based on the bifurcation nodes and paths taken\n if biff_node == 0:\n pass # Different paths taken at root\n elif biff_node is not None:\n # Removing the common path weights when paths diverge at a bifurcation node\n weights = [weights[i] - self.weight_summary[biff_node][i] * 2 for i in range(27)]\n else:\n # Adjusting weights based on the closer node to the root\n closer_node = start if sum(self.weight_summary[start]) < sum(self.weight_summary[end]) else end\n weights = [weights[i] - self.weight_summary[closer_node][i] * 2 for i in range(27)]\n \n # Calculating the final result for each query\n result[i] = sum(weights) - max(weights)\n \n return result\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA Explained solution C++ | lca-explained-solution-c-by-rajdeep_naga-7cgv | ```\n/\n\n\n1 <= wi <= 26\n\nfirst we make any node as root node\n\nthen we store frequency of each wight from root node to node x in freq[x][wt]\n\n\nfor path | Rajdeep_Nagar | NORMAL | 2023-10-06T05:58:50.212694+00:00 | 2023-10-06T05:58:50.212713+00:00 | 9 | false | ```\n/*\n\n\n1 <= wi <= 26\n\nfirst we make any node as root node\n\nthen we store frequency of each wight from root node to node x in freq[x][wt]\n\n\nfor path from a to b\n\nfirst we find lca(a,b)\n\nthen we can check frequency of each weight between lca -----a and lca ------b \n\noptimally using freq as - \n\nThe frequency of edge weight w on the path from a to b is equal to freq[a][w] + freq[b][w] - freq[lca(a,b)][w] * 2\n\n*/\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& qr) {\n \n \n vector<pair<int,int>>g[n];\n \n for(auto it:edges){\n\n g[it[0]].push_back({it[1],it[2]});\n g[it[1]].push_back({it[0],it[2]});\n\n }\n \n \n // root = 0, STORING WEIGHT FREQUENCY PROCESSING\n \n vector<vector<int>>freq(n,vector<int>(27,0));\n \n queue<int>q;\n \n q.push(0);\n \n vector<bool>vis(n,false);\n \n vis[0]=true;\n \n while(!q.empty()){\n int sz=q.size();\n while(sz--){\n int x=q.front();\n q.pop();\n for(auto y:g[x]){\n if(vis[y.first]==false){\n vis[y.first]=true;\n for(int w=1;w<=26;w++)\n freq[y.first][w]=freq[x][w];\n \n freq[y.first][y.second]++;\n \n q.push(y.first);\n }\n }\n }\n }\n \n \n // LCA PROCESSING\n \n int ht = (int)ceil(log2(n));\n \n vector<vector<int>>dp(n, vector<int>(ht + 1, -1));\n \n vector<int> height(n);\n \n \n dfs(0, 0, dp, height, ht, g); // root = 0\n \n int m=qr.size();\n \n vector<int>ans(m);\n \n\n \n for(int i=0;i<m;i++){\n int u=qr[i][0];\n \n int v=qr[i][1];\n \n int lc_a = lca(u,v,ht,height, dp);\n \n int mn=1e5;\n \n \n for(int w=1;w<=26;w++){\n int edgeCount=height[u]-height[lc_a] + height[v]-height[lc_a];\n int whtFreq=freq[u][w]+freq[v][w]-freq[lc_a][w]*2;\n\n mn=min(mn,edgeCount-whtFreq);\n }\n \n ans[i]=mn;\n }\n \n \n return ans;\n \n }\n \n \nvoid dfs(int u, int p, vector<vector<int>>&dp, vector<int> &height, int ht, vector<pair<int,int>>g[])\n{\n\n dp[u][0] = p;\n for (int i = 1; i <= ht; i++)\n dp[u][i] = dp[dp[u][i - 1]][i - 1];\n\n for (auto v : g[u])\n {\n if (v.first != p)\n {\n height[v.first] = height[u] + 1;\n dfs(v.first, u, dp, height, ht, g);\n }\n }\n}\n\n \n \nint lca(int u, int v, int ht, vector<int> &height, vector<vector<int>>&dp)\n{\n\n if (height[u] < height[v])\n swap(u, v);\n\n for (int i = ht; i >= 0; i--)\n if ((height[u] - pow(2, i)) >= height[v])\n u = dp[u][i];\n if (u == v)\n return u;\n\n for (int i = ht; i >= 0; i--)\n {\n if (dp[u][i] != dp[v][i])\n {\n u = dp[u][i];\n v = dp[v][i];\n }\n }\n\n return dp[u][0];\n}\n\n}; | 0 | 0 | ['C', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ LCA solution (binary lifting) O(N * log N) solution, clean code | c-lca-solution-binary-lifting-on-log-n-s-yvqf | \nusing WeightedGraph = vector<vector<pair<int, int>>>;\n\nclass LCA {\npublic:\n LCA(int n, const WeightedGraph& g): l(ceil(log2(n))), dp(init(n, g)), in(n) | dmitrii_bokovikov | NORMAL | 2023-09-22T14:29:20.711663+00:00 | 2023-09-22T14:29:20.711681+00:00 | 9 | false | ```\nusing WeightedGraph = vector<vector<pair<int, int>>>;\n\nclass LCA {\npublic:\n LCA(int n, const WeightedGraph& g): l(ceil(log2(n))), dp(init(n, g)), in(n), out(n) {}\n\n int get(int v, int t) {\n if (isAncestor(v, t)) {\n return v;\n }\n for (int i = l; i >= 0; --i) {\n if (!isAncestor(dp[v][i], t)) {\n v = dp[v][i];\n }\n }\n return dp[v][0];\n }\n\nprivate:\n bool isAncestor(int v, int t) {\n return in[v] <= in[t] && out[v] >= out[t];\n }\n\n vector<vector<int>> init(int n, const WeightedGraph& g) {\n vector<vector<int>> res(n, vector<int>(l + 1));\n int timer = 0;\n function<void(int, int)> dfs;\n dfs = [&](int v, int p) {\n in[v] = timer++;\n res[v][0] = p;\n for (int i = 1; i <= l; ++i) {\n res[v][i] = res[res[v][i - 1]][i - 1];\n }\n for (const auto [to, _]: g[v]) {\n if (to != p) {\n dfs(to, v);\n }\n }\n out[v] = timer++;\n };\n dfs(0, 0);\n return res;\n }\n\n const int l;\n vector<int> in;\n vector<int> out;\n const vector<vector<int>> dp;\n};\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n WeightedGraph g(n);\n for (const auto& e: edges) {\n g[e[0]].emplace_back(e[1], e[2]);\n g[e[1]].emplace_back(e[0], e[2]);\n }\n LCA lca(n, g);\n vector<vector<int>> values(n, vector<int>(26));\n vector<int> current(27);\n function<void(int v, int p)> dfs;\n dfs = [&](int v, int p) {\n values[v] = current;\n for (const auto[to, val]: g[v]) {\n if (to == p) {\n continue;\n }\n ++current[val];\n dfs(to, v);\n --current[val];\n }\n };\n dfs(0, 0);\n\n const auto plus = [](const vector<int>& v1, const vector<int>& v2) {\n vector<int> res(size(v1));\n for (int i = 0; i < size(v1); ++i) {\n res[i] = v1[i] + v2[i];\n }\n return res;\n };\n\n const auto minus = [](const vector<int>& v1, const vector<int>& v2) {\n vector<int> res(size(v1));\n for (int i = 0; i < size(v1); ++i) {\n res[i] = v1[i] - v2[i];\n }\n return res;\n };\n\n const auto getSteps = [](const vector<int>& v) {\n int edgesCount = 0;\n int maxFreaquncy = 0;\n for (const auto val: v) {\n edgesCount += val;\n maxFreaquncy = max(maxFreaquncy, val);\n }\n return edgesCount - maxFreaquncy;\n };\n\n vector<int> ans;\n for (const auto& q: queries) {\n const auto ancestor = lca.get(q[0], q[1]);\n ans.push_back(\n getSteps(\n minus(\n minus(\n plus(\n values[q[0]], \n values[q[1]]),\n values[ancestor]\n ),\n values[ancestor]\n )\n )\n );\n \n }\n return ans;\n }\n};\n\n\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ Super Easy to understand , No extra logic | c-super-easy-to-understand-no-extra-logi-dcfr | Intuition\n\nFind the ancestor then calculating the difference of count;\n\n# Approach\n\nBinary lifting setting then traverval, holding count of weights\n\n# C | udaysinghp95 | NORMAL | 2023-09-17T19:42:18.348757+00:00 | 2023-09-17T19:42:52.885462+00:00 | 14 | false | # Intuition\n\nFind the ancestor then calculating the difference of count;\n\n# Approach\n\nBinary lifting setting then traverval, holding count of weights\n\n# Complexity\n Time complexity:\n - O(N*32)\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<vector<int>> dist;\n vector<vector<int>> bl;\n vector<int> level;\n int bit;\n \n void helper(vector<vector<pair<int,int>>> &path,int p,int g,int l)\n {\n \n level[p]=l;\n bl[p][0]=g;\n\n\n for(int i=1;i<bit;i++)\n if(bl[p][i-1]!=-1)\n {\n bl[p][i]=bl[bl[p][i-1]][i-1];\n \n }\n else break;\n\n\n for(auto [c,w]:path[p])\n if(c!=g)\n {\n dist[c]=dist[p];\n dist[c][w]++;\n helper(path,c,p,l+1);\n } \n \n\n \n }\n\n int ancestor(int a,int b)\n {\n if(level[a]>level[b])\n swap(a,b);\n\n int k=level[b]-level[a];\n\n for(int i=0;i<bit;i++)\n if(k&(1<<i))\n {\n\n b=bl[b][i];\n }\n \n if(a==b)\n return a;\n \n for(int i=bit-1;i>=0;i--)\n if(bl[a][i]!=bl[b][i])\n {\n a=bl[a][i];\n b=bl[b][i];\n }\n\n\n return bl[a][0];\n }\n\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) \n {\n vector<vector<pair<int,int>>> path(n);\n\n for(auto p:edges)\n {\n path[p[1]].push_back({p[0],p[2]});\n path[p[0]].push_back({p[1],p[2]});\n }\n\n bl.assign(n,vector<int>(32,-1));\n level.assign(n,0);\n dist.assign(n,vector<int>(27,0));\n bit=32;\n helper(path,0,-1,0);\n\n vector<int> res;\n\n for(auto q:queries)\n {\n int a=q[0];\n int b=q[1];\n\n int p=ancestor(a,b);\n\n int sum=0;\n int val=0;\n\n for(int i=0;i<27;i++)\n {\n int v=dist[a][i]+dist[b][i]-dist[p][i]*2;\n val=max(val,v);\n sum+=v;\n }\n\n res.push_back(sum-val);\n }\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Minimum Edge Weight Equilibrium Queries in a Tree | minimum-edge-weight-equilibrium-queries-z3tj6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Sam_Neamah | NORMAL | 2023-09-16T03:03:43.468099+00:00 | 2023-09-16T03:03:43.468118+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar minOperationsQueries = function(n, edges, queries) {\n const kMax = 26;\n const m = Math.floor(Math.log2(n)) + 1;\n const ans = new Array(queries.length);\n const graph = new Array(n).fill(null).map(() => []);\n // jump[i][j] := node you reach after jumping 2^j from i\n const jump = new Array(n).fill(null).map(() => new Array(m).fill(0));\n // count[i][j] := count of j from root to i, where 1 <= j <= 26\n const count = new Array(n).fill(null).map(() => []);\n // depth[i] := depth of i\n const depth = new Array(n).fill(0);\n for (let i = 0; i < n; ++i){\n graph[i] = [];\n }\n for (const edge of edges) {\n const u = edge[0];\n const v = edge[1];\n const w = edge[2];\n graph[u].push([v, w]);\n graph[v].push([u, w]);\n }\n count[0] = new Array(kMax + 1).fill(0);\n dfs(graph, 0, -1, 0, jump, count, depth);\n // Binary lifting.\n for (let j = 1; j < m; ++j){\n for (let i = 0; i < n; ++i){\n jump[i][j] = jump[jump[i][j - 1]][j - 1];\n }\n }\n for (let i = 0; i < queries.length; ++i) {\n const u = queries[i][0];\n const v = queries[i][1];\n const lca = getLCA(u, v, jump, depth);\n // # of edges between (u, v).\n const numEdges = depth[u] + depth[v] - 2 * depth[lca];\n // max frequency of edges between (u, v)\n let maxFreq = 0;\n for (let j = 1; j <= kMax; ++j){\n maxFreq = Math.max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]);\n }\n ans[i] = numEdges - maxFreq;\n }\n return ans;\n}\ndfs= (graph, u, prev, d, jump, count, depth)=> {\n if (prev !== -1)\n jump[u][0] = prev;\n depth[u] = d;\n for (const pair of graph[u]) {\n const v = pair[0];\n const w = pair[1];\n if (v === prev)\n continue;\n // Inherit count from parent.\n count[v] = [...count[u]];\n // Add one to this edge.\n ++count[v][w];\n dfs(graph, v, u, d + 1, jump, count, depth);\n }\n}\n// Returns the lca(u, v) via binary lifting.\nconst getLCA=(u, v, jump, depth)=> {\n // v is always deeper than u.\n if (depth[u] > depth[v])\n return getLCA(v, u, jump, depth);\n // Jump v to the same height of u.\n for (let j = 0; j < jump[0].length; ++j)\n if (((depth[v] - depth[u]) >> j & 1) === 1)\n v = jump[v][j];\n if (u === v)\n return u;\n // Jump u and v to the node right below the lca.\n for (let j = jump[0].length - 1; j >= 0; --j)\n if (jump[u][j] !== jump[v][j]) {\n u = jump[u][j];\n v = jump[v][j];\n }\n return jump[v][0];\n}\n``` | 0 | 0 | ['JavaScript'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | ✅ C++ | Binary Lifting🔥🔥 | LCA | 🚀🚀 Simple🔥 Clean Code | Easy to Understand✅✅ | c-binary-lifting-lca-simple-clean-code-e-ipzd | \n# AUTHOR: JAYESH BADGUJAR\n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>> dp;\nvector<int> height;\n\n void dfs(int src,map<int,vector<pair<in | Jayesh_06 | NORMAL | 2023-09-12T10:50:52.058601+00:00 | 2023-09-12T10:50:52.058621+00:00 | 11 | false | \n# AUTHOR: JAYESH BADGUJAR\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> dp;\nvector<int> height;\n\n void dfs(int src,map<int,vector<pair<int,int>>>& mp,map<int,vector<int>>& prefix,vector<int>& dist,vector<int>& fre,int par,int c){\n \n prefix[src]=fre;\n dist[src]=c;\n dp[src][0] = par;\n height[src] = c;\n for(int i = 1 ; i < 15 ; ++i)\n if(dp[src][i-1] != -1) dp[src][i] = dp[dp[src][i-1]][i-1];\n\n\n for(auto it:mp[src]){\n if(it.first!=par){\n fre[it.second]++;\n dfs(it.first,mp,prefix,dist,fre,src,c+1);\n fre[it.second]--;\n }\n }\n \n }\n int lift(int node,int jump)\n {\n for(int i = 14 ; i >= 0 ; --i)\n {\n if(node == -1) return node;\n if(jump&(1<<i))\n node = dp[node][i];\n }\n return node;\n }\n int ancestor(int a,int b)\n {\n if(height[a] < height[b]) swap(a,b);\n a = lift(a,height[a]-height[b]);\n if(a == b) return a;\n for(int i = 14 ; i >= 0 ; --i)\n {\n if(dp[a][i] != dp[b][i])\n {\n a = dp[a][i];\n b = dp[b][i];\n }\n }\n\t return lift(a,1);\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n height = vector<int>(n);\n dp = vector<vector<int>>(n,vector<int>(15,-1));\n vector<int> ans;\n map<int,vector<int>> prefix;\n map<int,vector<pair<int,int>>> mp;\n for(int i=0;i<edges.size();i++){\n mp[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n mp[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n vector<int> dist(n,0),fre(27,0);\n dfs(0,mp,prefix,dist,fre,-1,0);\n for(int i=0;i<queries.size();i++){\n int start=queries[i][0],end=queries[i][1];\n vector<int> end_prefix=prefix[end];\n vector<int> start_prefix=prefix[start];\n int lca = ancestor(start,end);\n int d=dist[end]+dist[start]-2*dist[lca];\n int maxi=0;\n for(int i=0;i<end_prefix.size();i++){\n end_prefix[i]=end_prefix[i]+start_prefix[i]-2*prefix[lca][i];\n maxi=max(maxi,end_prefix[i]);\n }\n ans.push_back(d-maxi);\n\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Tree', 'Graph', 'Strongly Connected Component', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ solution using binary lifting | c-solution-using-binary-lifting-by-sting-gp03 | Code\n\nclass Solution {\npublic:\n vector<int>parent;\n vector<int>level;\n int dp[10001][20];\n vector<vector<int>>edgeWeights;\n\n void markPa | Sting285 | NORMAL | 2023-09-10T17:18:52.165144+00:00 | 2023-09-10T17:18:52.165181+00:00 | 18 | false | # Code\n```\nclass Solution {\npublic:\n vector<int>parent;\n vector<int>level;\n int dp[10001][20];\n vector<vector<int>>edgeWeights;\n\n void markParent(vector<vector<int>>adj[]){\n queue<int>q;\n q.push(0);\n parent[0] = -1;\n int count = -1;\n\n while(!q.empty()){\n int size = q.size();\n ++count;\n for(int i=0;i<size;i++){\n int temp = q.front();\n q.pop();\n\n level[temp] = count;\n\n for(auto it: adj[temp]){\n int node = it[0];\n if(parent[temp] == node)\n continue;\n parent[node] = temp;\n q.push(node);\n }\n }\n }\n }\n\n void dfs(int node, vector<vector<int>>adj[]){\n dp[node][0] = parent[node];\n\n for(int i=1;i<20;i++){\n int temp = dp[node][i-1];\n if(temp!=-1){\n dp[node][i] = dp[temp][i-1];\n }\n else\n break;\n }\n\n for(auto it: adj[node]){\n int temp = it[0];\n if(parent[node] == temp)\n continue;\n dfs(temp, adj);\n }\n }\n\n void storeEdges(int node, vector<vector<int>>adj[], vector<int>&curr){\n edgeWeights[node] = curr;\n\n for(auto it: adj[node]){\n int temp = it[0];\n int wt = it[1];\n\n if(parent[node] == temp) \n continue;\n \n curr[wt]+=1;\n storeEdges(temp, adj, curr);\n curr[wt]-=1;\n }\n }\n\n int getLCA(int a, int b){\n int levela = level[a];\n int levelb = level[b];\n\n if(levela < levelb){\n swap(a, b);\n swap(levela, levelb);\n }\n\n int diff = levela - levelb;\n for(int i=19;i>=0;i--){\n if((diff>>i) & 1){\n a = dp[a][i];\n }\n }\n\n if(a == b)\n return a;\n\n for(int i=19;i>=0;i--){\n int tmp1 = dp[a][i];\n int tmp2 = dp[b][i];\n if(tmp1 != tmp2){\n a = dp[a][i];\n b = dp[b][i];\n }\n }\n\n return dp[a][0];\n }\n\n int solve(int a, int b){\n int lca = getLCA(a, b);\n vector<int>curr(27, 0);\n\n auto lcaMap = edgeWeights[lca];\n auto aMap = edgeWeights[a];\n auto bMap = edgeWeights[b];\n\n for(int i=0;i<27;i++){\n curr[i]+= aMap[i] - lcaMap[i];\n }\n\n for(int i=0;i<27;i++){\n curr[i]+= bMap[i] - lcaMap[i];\n }\n\n int total = 0, maxi = 0;\n for(auto it: curr){\n total+=it;\n maxi = max(maxi, it);\n }\n\n return total - maxi;\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<int>>adj[n];\n for(int i=0;i<edges.size();i++){\n int a = edges[i][0];\n int b = edges[i][1];\n int wt = edges[i][2];\n\n adj[a].push_back({b, wt});\n adj[b].push_back({a, wt});\n }\n\n parent.resize(n, 0);\n level.resize(n, 0);\n edgeWeights.resize(n);\n\n markParent(adj);\n memset(dp, -1, sizeof(dp));\n\n dfs(0, adj);\n\n vector<int>curr(27, 0);\n storeEdges(0, adj, curr);\n\n vector<int>res;\n\n for(auto it: queries){\n int ans = solve(it[0], it[1]);\n res.push_back(ans);\n }\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | JAVA || DFS || BINARY LIFTING || BINARY SEARCH || LCA | java-dfs-binary-lifting-binary-search-lc-spg2 | Intuition\n Describe your first thoughts on how to solve this problem. \nNeed knowledge of binary lifting and getting lca using it to get this\n# Approach\n Des | viratt15081990 | NORMAL | 2023-09-09T19:01:35.051168+00:00 | 2023-09-09T19:02:31.626336+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNeed knowledge of binary lifting and getting lca using it to get this\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe use 0 as root, and store weight freq of each node from it with help of dfs, since weigh range is it (1,25). we process our graph for getting up array needed for binary lifting. and calculate lca of src and dest using binary lifting and binary search, then to process result, we have weight patg from 0 to src via lca, and 0 to dest via lca.\n\n# Complexity\n- Time complexity: O(N*27)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N*27)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n class Node{\n int v;\n int w;\n Node(int v,int w){\n this.v=v;\n this.w=w;\n }\n }\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n List<List<Node>> graph = createGraph(edges,n);\n int queryCount = queries.length;\n int [] res = new int[queryCount];\n int [] parent = new int [n];\n int [] level = new int [n];\n int [][] weightFreq = new int [n][27];\n int [] freq = new int [27];\n int height = (int)(Math.log(n)/Math.log(2))+1;\n int [][] up = new int[n][height];\n for(int [] arr:up){\n Arrays.fill(arr,-1);\n }\n \n dfs(graph,0,0,-1,parent,level,weightFreq,freq);\n \n for(int i=0;i<n;i++){\n up[i][0]=parent[i];\n }\n for(int i=1;i<height;i++){\n for(int j=0;j<n;j++){\n if(up[j][i-1]==-1){\n up[j][i]=-1;\n continue;\n }\n up[j][i]= up[up[j][i-1]][i-1];\n }\n }\n for(int i=0;i<queryCount;i++){\n int src = queries[i][0];\n int dest = queries[i][1];\n int lcaNode = lca(n,src,dest,up,height,level);\n //System.out.print(lcaNode+" ");\n res[i]=processResult(weightFreq[src],weightFreq[dest],weightFreq[lcaNode]);\n }\n \n return res;\n }\n public int lca(int n,int src,int dest,int [][] up,int height,int []level){\n int curr1 = src;\n int curr2 = dest;\n int minlevel;\n if(level[curr1]>level[curr2]){\n minlevel = level[curr2];\n curr1=getKthAncestor(curr1,level[curr1]-level[curr2],up,height);\n }else if(level[curr1]<=level[curr2]){\n minlevel = level[curr1];\n curr2=getKthAncestor(curr2,level[curr2]-level[curr1],up,height);\n }else{\n minlevel = level[curr1];\n }\n //System.out.println(level[curr2]+" "+level[curr1]);\n if(curr1==curr2) return curr1;\n int l=0;\n int h=level[curr2];\n while(l<=h){\n int mid = l+(h-l)/2;\n int p1 = getKthAncestor(curr1,minlevel-mid,up,height);\n int p2 = getKthAncestor(curr2,minlevel-mid,up,height);\n if(p1==p2){\n l=mid+1;\n }else{\n h=mid-1;\n }\n }\n return getKthAncestor(curr1,minlevel-l+1,up,height);\n \n \n }\n public int getKthAncestor(int node, int k,int [][] up,int height) {\n int curr=node;\n for(int i=0;i<height && k>>i!=0;i++){\n if(((1<<i) & k) !=0){\n if(curr==-1){\n return -1;\n }\n curr = up[curr][i];\n }\n }\n return curr;\n }\n private int processResult(int [] freqSrc,int []freqDest,int []freqLCA){\n int [] freqPath = new int [27];\n for(int i=1;i<27;i++){\n freqPath[i] = freqSrc[i] + freqDest[i] - 2*freqLCA[i];\n }\n int max = 0;\n int pathlen = 0;\n for(int i=1;i<27;i++){\n max = Math.max(max,freqPath[i]);\n pathlen += freqPath[i];\n }\n return pathlen-max;\n }\n \n \n public void dfs(List<List<Node>> graph,int src,int currlevel,int p,int [] parent, int []level,int [][] weightFreq,int []freq){\n parent[src]=p;\n level[src]=currlevel;\n for(int i=0;i<freq.length;i++){\n weightFreq[src][i]=freq[i];\n }\n for(Node node:graph.get(src)){\n int v=node.v;\n int w=node.w;\n if(v!=p){\n freq[w]++;\n dfs(graph,v,currlevel+1,src,parent,level,weightFreq,freq);\n freq[w]--;\n }\n }\n }\n \n private List<List<Node>> createGraph(int[][] edges,int n){\n List<List<Node>> graph = new ArrayList<>();\n for(int i=0;i<n;i++){\n graph.add(new ArrayList<>());\n }\n for(int [] edge:edges){\n int u = edge[0];\n int v = edge[1];\n int w = edge[2];\n graph.get(u).add(new Node(v,w));\n graph.get(v).add(new Node(u,w));\n }\n return graph;\n }\n}\n``` | 0 | 1 | ['Binary Search', 'Depth-First Search', 'Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA + parent node prefix sums | lca-parent-node-prefix-sums-by-miteshkum-2ll5 | Intuition\nLCA + Parent node prefix sums\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\nO(Q * W * log(n)) | miteshkumar_ | NORMAL | 2023-09-09T14:20:43.729295+00:00 | 2023-09-09T14:20:43.729312+00:00 | 11 | false | # Intuition\nLCA + Parent node prefix sums\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(Q * W * log(n)) + O(n log(n))\n- Space complexity:\nO(N log (N) * W)\n# Code\n```\nusing ll = long long;\nconstexpr ll P = 14;\nconstexpr ll W = 26;\nclass Solution {\npublic:\n struct Node\n {\n ll pre{-1};\n ll post{-1};\n std::array<Node*, P> parent {nullptr};\n std::array<ll, W> wts{0};\n std::vector<std::pair<Node*, ll>> children;\n };\n\n inline void initialize(Node* node, Node* parent, ll& counter)\n {\n node->pre = counter++;\n node->parent[0] = parent;\n for (ll i = 1; i < P; ++i) {\n if (node->parent[i-1]) {\n node->parent[i] = (node->parent[i-1])->parent[i-1];\n }\n }\n\n for (auto& [child, edge_wt] : node->children) {\n if (child == parent) continue;\n child->wts = node->wts;\n ++child->wts[edge_wt];\n initialize(child, node, counter);\n }\n node->post = counter++;\n }\n\n inline bool isAncestor(Node* ancestor, Node* descendant) {\n return (ancestor->pre <= descendant->pre) \n && (ancestor->post >= descendant->post);\n }\n\n inline Node* findLargest(Node* a, Node* b) {\n assert(not isAncestor(a, b));\n assert(not isAncestor(b, a));\n Node* ans {b};\n for (ll i = 0; i < P; ++i) {\n if (not b->parent[i]) break;\n if (not isAncestor(b->parent[i], a)) {\n ans = b->parent[i];\n } else break;\n }\n assert(ans);\n assert(not isAncestor(ans, a));\n assert(ans->parent[0]);\n return ans->parent[0];\n }\n\n inline Node* lca(Node* a, Node* b) {\n if (isAncestor(a, b)) {\n return a;\n } else if (isAncestor(b, a)) {\n return b;\n } else {\n return lca(findLargest(b, a), b);\n }\n }\n\n inline vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n std::vector<Node> tree(n, Node{});\n for (auto const& e : edges) {\n tree[e[0]].children.push_back({&tree[e[1]], static_cast<ll>(e[2]-1)});\n tree[e[1]].children.push_back({&tree[e[0]], static_cast<ll>(e[2]-1)});\n }\n {\n ll counter = 0;\n initialize(&tree[0], nullptr, counter);\n }\n const ll Q = queries.size();\n vector<int> ans(Q);\n for (ll q = 0; q < Q; ++q) {\n ll sum { 0 };\n ll best { 0 };\n Node* a = &tree[queries[q][0]];\n Node* b = &tree[queries[q][1]];\n Node* p = lca(a, b);\n for (ll i = 0; i < W; ++i) {\n const ll cur = (a->wts[i] - p->wts[i]) + (b->wts[i] - p->wts[i]);\n best = max(best, cur);\n sum += cur;\n }\n ans[q] = sum - best;\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA using Binary Lifting and Frequency DP. | lca-using-binary-lifting-and-frequency-d-94z7 | \nclass Solution {\n int [][]parent; // parent[jump][node] for LCA via binary lifting. \n int []levels;\n int [][] freq;\n Map<Integer, List<int[]>> | namandeept | NORMAL | 2023-09-09T09:45:02.716450+00:00 | 2023-09-09T09:45:02.716473+00:00 | 6 | false | ```\nclass Solution {\n int [][]parent; // parent[jump][node] for LCA via binary lifting. \n int []levels;\n int [][] freq;\n Map<Integer, List<int[]>> graph;\n \n public void DFS(int node, int par) {\n parent[0][node] = par;\n levels[node] = levels[par] + 1;\n for(int j=1; j<=15; j++) {\n parent[j][node] = parent[j-1][parent[j-1][node]];\n }\n if(graph.containsKey(node)) {\n for(int []children : graph.get(node)) {\n if(children[0] == par) continue;\n int child = children[0], weight = children[1];\n for(int i=0; i<26; i++) {\n if(weight == i) {\n freq[child][i] = freq[node][i] + 1;\n }\n else freq[child][i] = freq[node][i];\n }\n DFS(child, node);\n } \n }\n \n }\n \n public int moveUP(int node, int level) {\n for(int j=0; j<=15; j++) {\n if((level & (1 << j)) != 0) {\n node = parent[j][node];\n }\n }\n return node;\n }\n\n public int lca(int x, int y) {\n if(levels[x] > levels[y]) {\n int temp = x;\n x = y;\n y = temp;\n }\n \n y = moveUP(y, levels[y] - levels[x]);\n if(x == y) return y;\n for(int i=15; i>=0; i--) {\n if(parent[i][x] != parent[i][y]) {\n x = parent[i][x];\n y = parent[i][y];\n }\n }\n return parent[0][x];\n }\n \n public int[] createArray(int x, int y, int lca) {\n int []frequency = new int[26];\n for(int i=0; i<26; i++) {\n frequency[i] = freq[x][i] + freq[y][i] - 2 * freq[lca][i];\n }\n return frequency;\n }\n \n public int calculateRes(int []freq) {\n int sum = 0, maxFreq = 0;\n for(int f : freq) {\n maxFreq = Math.max(maxFreq, f);\n sum += f;\n }\n return sum - maxFreq;\n }\n \n public void constructGraph(int [][]edges) {\n for(int []edge : edges) {\n int from = edge[0] + 1, to = edge[1] + 1, weight = edge[2] - 1;\n if(!graph.containsKey(from)) {\n graph.put(from, new ArrayList<>());\n }\n if(!graph.containsKey(to)) {\n graph.put(to, new ArrayList<>());\n }\n graph.get(from).add(new int[]{to, weight});\n graph.get(to).add(new int[]{from, weight});\n }\n }\n \n \n \n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n int []inDegree = new int[n];\n parent = new int[16][n + 1];\n levels = new int[n + 1];\n freq = new int[n + 1][26];\n graph = new HashMap<>();\n \n constructGraph(edges);\n \n DFS(1, 0);\n int []minOp = new int[queries.length];\n for(int i=0; i < queries.length; i++) {\n int start = queries[i][0] + 1, end = queries[i][1] + 1;\n int lca = lca(start, end);\n minOp[i] = calculateRes(createArray(start, end, lca));\n }\n return minOp;\n }\n}\n``` | 0 | 0 | [] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ | c-by-big_chill-jrvv | Intuition\n Describe your first thoughts on how to solve this problem. Binary lifting\n\n# Approach\n Describe your approach to solving the problem. \n\n# Compl | Big_chill | NORMAL | 2023-09-09T07:07:43.300178+00:00 | 2023-09-09T07:07:43.300196+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->Binary lifting\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nconst int N = 1e4+5;\nconst int M = 15;\nconst int P = 27;\nint up[N][M];\nint height[N];\nint W[N][M][P];\n\nclass Solution {\npublic:\n void DFS(int v , vector<vector<pair<int,int>>> &adj , int p)\n {\n for(auto &pu:adj[v])\n {\n int u = pu.first;\n // int w = pu.second;\n\n if(u!=p)\n {\n height[u] = height[v]+1;\n up[u][0] = v;\n for(int i=1;i<M;i++)\n {\n up[u][i] = up[up[u][i-1]][i-1];\n }\n DFS(u,adj,v);\n }\n }\n return;\n }\n void DFSW(int v , vector<vector<pair<int,int>>> &adj , int p)\n {\n for(auto &pu:adj[v])\n {\n int u = pu.first;\n int w = pu.second;\n\n if(u!=p)\n {\n W[u][0][w]++;\n for(int i=1;i<M;i++)\n {\n for(int j=1;j<P;j++)\n {\n W[u][i][j] = W[u][i-1][j] + W[up[u][i-1]][i-1][j];\n }\n }\n DFSW(u,adj,v);\n }\n }\n return;\n }\n void clearAll(int n)\n {\n for(int i=0;i<n;i++)\n {\n height[i]=0;\n for(int j=0;j<M;j++)\n {\n up[i][j]=0;\n for(int k=0;k<P;k++)\n {\n W[i][j][k]=0;\n }\n }\n }\n return;\n }\n int kthAncestor(int x,int k)\n {\n for(int i=0;i<M;i++)\n {\n if(k&(1<<i)){\n x=up[x][i];\n }\n }\n return x;\n }\n int lca(int x,int y)\n {\n if(height[x]<height[y]) swap(x,y);\n x = kthAncestor(x,height[x]-height[y]);\n if(x==y) return x;\n for(int i=M-1;i>=0;i--)\n {\n if(up[x][i]!=up[y][i])\n {\n x=up[x][i];\n y=up[y][i];\n }\n }\n return up[x][0];\n }\n vector<int> kthAncestorWarray(int x,int k){\n vector<int> res(P);\n for(int i=0;i<M;i++)\n {\n if(k&(1<<i))\n {\n for(int j=0;j<P;j++)\n {\n res[j]+= W[x][i][j];\n }\n x=up[x][i];\n }\n }\n return res;\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n clearAll(n);\n vector<vector<pair<int,int>>> adj(n);\n for(int i=0;i<edges.size();i++)\n {\n adj[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n adj[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n DFS(0,adj,-1);\n DFSW(0,adj,-1);\n vector<int> ans;\n for(int k=0;k<queries.size();k++)\n {\n int x = queries[k][0];\n int y = queries[k][1];\n int z = lca(x,y);\n vector<int> wx = kthAncestorWarray(x,height[x]-height[z]);\n vector<int> wy = kthAncestorWarray(y,height[y]-height[z]);\n int freq=0;\n for(int i=0;i<P;i++)\n {\n freq = max(freq,wx[i]+wy[i]);\n }\n ans.push_back(height[x]+height[y]-2*height[z] - freq);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | EASY BINARY LIFTING WITH TEMPLATE | easy-binary-lifting-with-template-by-dvs-e1eu | Approach\nThis is a classic Binary Lifting problem where we have to find LCA\nin the most optimal time.I simply copy pasted the approach to find LCA from this t | DVSINGH | NORMAL | 2023-09-08T13:06:29.704261+00:00 | 2023-09-08T13:06:29.704293+00:00 | 24 | false | # Approach\nThis is a classic Binary Lifting problem where we have to find LCA\nin the most optimal time.I simply copy pasted the approach to find LCA from this template.It captures LCA in logn time.-\n\n```\nvector<vector<int>> adj;\nvector<int> parent, depth;\n\nvector<vector<int>> table;\nint tableSize;\n\nvoid fillTable(vector<int>& parent) {\n\tint n = parent.size();\n\ttableSize = ceil(log2(n));\n\n\ttable = vector<vector<int>>(n, vector<int>(tableSize + 1));\n\n\tfor(int node = 0; node < n; node++) {\n\t\ttable[node][0] = parent[node];\n\t}\n\n\tfor(int k = 1; k <= tableSize; k++)\n\t\tfor(int node = 0; node < n; node++)\n\t\t\ttable[node][k] = table[table[node][k-1]][k-1];\n}\n\nint query(int node, int jump) {\n\tfor(int i = tableSize; i >= 0; i--)\n\t\tif(jump & (1 << i))\n\t\t\tnode = table[node][i];\n\treturn node;\n}\n\nint getLCABinaryLifting(int u, int v) {\n\tif(depth[u] > depth[v]) {\n\t\tint diff = depth[u] - depth[v];\n\t\tu = query(u, diff);\n\t}\n\n\tif(depth[v] > depth[u]) {\n\t\tint diff = depth[v] - depth[u];\n\t\tv = query(v, diff);\n\t}\n\n\tif(u == v) return u;\n\n\tfor(int i = tableSize; i >= 0; i--) {\n\t\tint newu = table[u][i];\n\t\tint newv = table[v][i];\n\n\t\tif(newu == newv) continue;\n\t\tu = newu;\n\t\tv = newv;\n\t}\n\n\treturn parent[u];\n}\n\nvoid dfs(int node, int par, int lev) {\n\tparent[node] = par;\n\tdepth[node] = lev;\n\tfor(auto child: adj[node]) \n\t\tif(child != par)\n\t\t\tdfs(child, node, lev + 1);\n}\n\nvector<int> lca(int n, vector<vector<int>> edges, vector<vector<int>> query) {\n\tadj = vector<vector<int>>(n);\n\tdepth = vector<int>(n);\n\tparent = vector<int>(n);\n\tfor(auto edge: edges) {\n\t\tint u = edge[0], v = edge[1];\n\t\tu--, v--;\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\n\tdfs(0, 0, 1);\n\tfillTable(parent);\n\n\tvector<int> res;\n\n\tfor(auto quer: query) {\n\t\tint u = quer[0], v = quer[1];\n\t\tu--, v--;\n\t\tint lca = getLCABinaryLifting(u, v);\n\t\tres.push_back(lca + 1);\n\t}\n\n\treturn res;\n}\n\n```\nAfter this,simply create a an auxillary function to calculate the frequency upto a particular point and then perform further calculations. \n\n\n# Code\n```\nclass Solution {\npublic:\nvector<vector<int>> adj;\nvector<int> parent, depth;\n\nvector<vector<int>> table;\nint tableSize;\n\nvoid fillTable(vector<int>& parent) {\n\tint n = parent.size();\n\ttableSize = ceil(log2(n));\n\n\ttable = vector<vector<int>>(n, vector<int>(tableSize + 1));\n\n\tfor(int node = 0; node < n; node++) {\n\t\ttable[node][0] = parent[node];\n\t}\n\n\tfor(int k = 1; k <= tableSize; k++)\n\t\tfor(int node = 0; node < n; node++)\n\t\t\ttable[node][k] = table[table[node][k-1]][k-1];\n}\n\nint query(int node, int jump) {\n\tfor(int i = tableSize; i >= 0; i--)\n\t\tif(jump & (1 << i))\n\t\t\tnode = table[node][i];\n\treturn node;\n}\n\nint getLCABinaryLifting(int u, int v) {\n\tif(depth[u] > depth[v]) {\n\t\tint diff = depth[u] - depth[v];\n\t\tu = query(u, diff);\n\t}\n\n\tif(depth[v] > depth[u]) {\n\t\tint diff = depth[v] - depth[u];\n\t\tv = query(v, diff);\n\t}\n\n\tif(u == v) return u;\n\n\tfor(int i = tableSize; i >= 0; i--) {\n\t\tint newu = table[u][i];\n\t\tint newv = table[v][i];\n\n\t\tif(newu == newv) continue;\n\t\tu = newu;\n\t\tv = newv;\n\t}\n\n\treturn parent[u];\n}\n\nvoid dfs(int node, int par, int lev) {\n\tparent[node] = par;\n\tdepth[node] = lev;\n\tfor(auto child: adj[node]) \n\t\tif(child != par)\n\t\t\tdfs(child, node, lev + 1);\n}\n\nvector<int> lca(int n, vector<vector<int>> adj, vector<vector<int>> query) {\n\t\n\n\tdfs(0, 0, 1);\n\tfillTable(parent);\n\n\tvector<int> res;\n\n\tfor(auto quer: query) {\n\t\tint u = quer[0], v = quer[1];\n\t\t\n\t\tint lca = getLCABinaryLifting(u, v);\n\t\tres.push_back(lca);\n\t}\n\n\treturn res;\n}\n\n\nvoid dfs2(vector<vector<int>> &freq,vector<int> &vis,int root,vector<vector<pair<int,int>>> &val){\n vis[root]=1;\n for(auto it:val[root]){\n int v=it.first,wt=it.second;\n if(!vis[v]){\n freq[v]=freq[root];\n freq[v][wt-1]++;\n dfs2(freq,vis,v,val);\n }\n }\n}\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n\n adj = vector<vector<int>>(n);\n\tdepth = vector<int>(n);\n\tparent = vector<int>(n);\n vector<vector<pair<int,int>>> val(n);\n\tfor(auto edge: edges) {\n\t\tint u = edge[0], v = edge[1];\n\t\t\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\n val[u].push_back({v,edge[2]});\n val[v].push_back({u,edge[2]});\n\n\t}\n \n vector<vector<int>> freq(n,vector<int> (26,0));\n vector<int> vis(n,0);\n\n dfs2(freq,vis,0,val);\n vector<int> ans;\n vector<int> l=lca(n,adj,queries);\n for(int i=0;i<queries.size();i++){\n int u=queries[i][0],v=queries[i][1];\n int m=l[i];\n int cnt=0,maxi=0;\n for(int j=0;j<26;j++){\n int a=(freq[u][j]-freq[m][j])+freq[v][j]-freq[m][j];\n if(a!=0){\n cnt+=a;\n maxi=max(maxi,a);\n }\n\n }\n ans.push_back(cnt-maxi);\n }\n\t\treturn ans;\n\n }\n};\n``` | 0 | 0 | ['Tree', 'Depth-First Search', 'Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA by Binary Lifting | lca-by-binary-lifting-by-dongts-k2c8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dongts | NORMAL | 2023-09-07T15:28:54.740398+00:00 | 2023-09-07T15:28:54.740425+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define pii pair<int,int>\n#define F first\n#define S second\n\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n // adj\n vector<vector<pii>> adj(n);\n for(auto&x:edges) {\n adj[x[0]].push_back({x[1],x[2]});\n adj[x[1]].push_back({x[0],x[2]});\n }\n // w[node][val] : count num of val in 0 to node\n vector<vector<int>> w(n, vector<int>(27));\n vector<int> uw(27);\n function<void(int,int)> dfsw=[&](int node,int pre_node) {\n for(int i=0; i<27; i++) {\n w[node][i] = uw[i];\n }\n for(auto&n_node:adj[node]) {\n if(n_node.F==pre_node) continue;\n uw[n_node.S]++;\n dfsw(n_node.F, node);\n uw[n_node.S]--;\n }\n };\n dfsw(0,-1);\n // h[node]: depth of node\n // parent[node]: parent of node\n vector<int> h(n), parent(n);\n function<void(int,int)> dfsh=[&](int node, int pre_node) {\n parent[node] = pre_node;\n for(auto&n_node:adj[node]) {\n if(n_node.F==pre_node) continue;\n h[n_node.F] = h[node]+1;\n dfsh(n_node.F, node);\n }\n };\n dfsh(0,-1);\n // up[node][15]: binary lifting\n vector<vector<int>> up(n, vector<int>(15));\n for(int i=0; i<n; i++) up[i][0] = parent[i];\n for(int bit=1; bit<15; bit++) {\n for(int i=0; i<n; i++) {\n if(up[i][bit-1]==-1) up[i][bit]=-1;\n else up[i][bit] = up[up[i][bit-1]][bit-1];\n }\n }\n // lca[u][v]: lca of u and v\n function<int(int,int)> lca=[&](int u, int v) {\n if(h[u]<h[v]) {\n swap(u,v);\n }\n int jump = h[u]-h[v];\n for(int i=0; i<15; i++) {\n if(jump&(1<<i)) {\n u=up[u][i];\n }\n }\n if(u==v) return u;\n for(int i=14; i>=0; i--) {\n if(up[u][i] == up[v][i]) continue;\n u=up[u][i];\n v=up[v][i];\n }\n return parent[u];\n };\n //\n vector<int> res;\n for(auto q:queries) {\n int u = q[0];\n int v = q[1];\n int l = lca(u,v);\n int leng = h[u]+h[v]-2*h[l];\n vector<int> w_q(27,0);\n int max_cnt = 0;\n for(int i=0; i<27; i++) {\n w_q[i] += w[u][i];\n w_q[i] += w[v][i];\n w_q[i] -= 2*w[l][i];\n max_cnt = max(max_cnt, w_q[i]);\n }\n res.push_back(leng - max_cnt);\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Python | LCA + PrefixSum | Simple Solution | python-lca-prefixsum-simple-solution-by-ow0ug | Code\n\nfrom collections import defaultdict\nfrom math import log2\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: | aryonbe | NORMAL | 2023-09-07T05:58:34.868371+00:00 | 2023-09-07T07:20:19.529161+00:00 | 22 | false | # Code\n```\nfrom collections import defaultdict\nfrom math import log2\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n G = defaultdict(list)\n for u,v,w in edges:\n G[u].append((v,w))\n G[v].append((u,w))\n m = int(log2(n)) + 1\n #lift[v][j]: 2^i th parent of node v\n lift = [[-1]*(m+1) for _ in range(n)]\n freq = [[0]*27 for _ in range(n)]\n depth = defaultdict(int)\n def dfs(u, prev):\n lift[u][0] = prev \n depth[u] = depth[prev] + 1 \n for j in range(1, m):\n lift[u][j] = lift[lift[u][j-1]][j-1]\n for v,w in G[u]:\n if v == prev: continue \n freq[v] = freq[u][:]\n freq[v][w] += 1 \n dfs(v, u)\n dfs(0, 0)\n def lca(u, v):\n if depth[u] > depth[v]: u,v = v,u \n for i in range(m):\n if (depth[v] - depth[u]) & (1<<i): v = lift[v][i]\n if u == v: return u \n for i in range(m-1, -1, -1):\n if lift[u][i] != lift[v][i]:\n u, v = lift[u][i], lift[v][i]\n return lift[u][0]\n res = []\n for u, v in queries:\n p = lca(u, v)\n count = [freq[u][w] + freq[v][w] - 2*freq[p][w] for w in range(27) ]\n res.append(sum(count) - max(count))\n return res \n\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | binary lifting for Lowest Common Ancestor | binary-lifting-for-lowest-common-ancesto-89or | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | zhouzilong2020 | NORMAL | 2023-09-06T15:18:23.753096+00:00 | 2023-09-06T15:18:23.753137+00:00 | 28 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n # node_weight[node][weight] = freq\n node_weight_freq = defaultdict(lambda: defaultdict(lambda : 0))\n # up[node][i] = 2^i th ancestor_node for current node\n up = defaultdict(list)\n # depth[node] = the depth of current node\n depth = defaultdict(lambda:0)\n\n G = defaultdict(list)\n for u,v,w in edges:\n G[u].append([v,w])\n G[v].append([u,w])\n\n def dfs(i, seen, weightCnt, path):\n for w, freq in weightCnt.items():\n node_weight_freq[i][w] = freq\n depth[i] = len(path) - 1\n \n if depth[i] > 0:\n for j in range(0, ceil(log2(depth[i]))):\n up[i].append(path[-2**j-1])\n up[i].append(path[0])\n\n for to, w in G[i]:\n if to in seen: continue\n seen.add(to)\n\n path.append(to)\n weightCnt[w] += 1\n dfs(to, seen, weightCnt, path)\n path.pop()\n weightCnt[w] -= 1\n\n dfs(0, set([0]), defaultdict(lambda: 0), [0])\n\n @cache\n def lca(u, v) -> int:\n # u alway points to the higher node\n if depth[u] > depth[v]: u,v = v, u\n if u == 0: return u\n # check if u is the ancesstor of v\n while depth[v] != depth[u]:\n depth_diff = depth[v] - depth[u]\n v = up[v][floor(log2(depth_diff))]\n if v == u: return u\n \n # u and v are on the same depth now, need to find their common ancesstor\n while up[u][0] != up[v][0]: \n max_diff = ceil(log2(depth[v]))+1\n for i in range(0, max_diff):\n if up[u][i] != up[v][i]:\n u = up[u][i]\n v = up[v][i]\n break\n\n return up[u][0]\n\n @cache\n def getAns(u,v):\n ancestor = lca(u,v)\n weight_freq = [node_weight_freq[u][i] + node_weight_freq[v][i] - 2*node_weight_freq[ancestor][i] for i in range(1,27)]\n return sum(weight_freq)-max(weight_freq)\n \n\n ans = []\n for u,v in queries:\n weight_freq = [0] * 27\n u,v = min(u,v), max(u,v)\n ans.append(getAns(u,v))\n\n return ans\n \n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Sparse Table, Binary Lifting, LCA, Tree Queries-> Commented Code | sparse-table-binary-lifting-lca-tree-que-dhis | \n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n O(nlog\u2061n+q(C+log\u2061n))\n\n- Space complexity:\n Add your space complexi | rahulhind | NORMAL | 2023-09-06T11:30:28.326856+00:00 | 2023-09-06T11:30:51.443950+00:00 | 13 | false | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(nlog\u2061n+q(C+log\u2061n))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(nlogn)$$\n\n# Code\n```\nclass Solution {\npublic:\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n\nvector<pair<int,int>>graph[n];\nfor(auto &e:edges){\n graph[e[0]].push_back({e[1],e[2]});\n graph[e[1]].push_back({e[0],e[2]});\n}\n//Sparse Table for Binnary Lifting //Table size of Log(N)\nvector<vector<int>>table(16,vector<int>(n));\n\n//Weight Table storing every child weight 1-26 for queries\nvector<vector<int>>weight(n,vector<int>(27));\nvector<int>height(n);\nfunction<void(int,int,int)>dfs=[&](int s,int p,int dep)->void{\n //Immediate Parent\n table[0][s]=p;\n height[s]=dep;\n for(int i=1;i<16;i++){\n table[i][s]=table[i-1][table[i-1][s]];\n }\n\n for(auto &[i,w]:graph[s]){\n if(i==p)continue;\n\n weight[i]=weight[s];\n weight[i][w]++;\n//Another way of doing this is below\n // weight[i][w]++;\n // for(int j = 0; j <27; j++)\n // weight[i][j] += weight[s][j];\n dfs(i,s,dep+1);\n \n } \n};\n\ndfs(0,0,0);\nauto lca=[&](int x,int y)->int{\n if(height[x]>height[y])swap(x,y);\n //To bring them in equal height first-> Moving Up to match the same height\n int dif=height[y]-height[x];\n for(int i=0;(1<<i)<=dif;i++){\n if(dif&(1<<i))y=table[i][y];\n }\n\n for(int i=15;i>=0;i--){\n if(table[i][x]!=table[i][y]){\n x=table[i][x];\n y=table[i][y];\n }\n }\n return x==y?x:table[0][x];\n\n};\nvector<int>ans;\nfor(auto q:queries){\n int x=q[0],y=q[1];\n int l=lca(x,y);\n //Inclusion Exclusion \n //Excluding repeating path to get the length between path X <-> Y\n int len=height[x]+height[y]-2*height[l];\n int mx=0;\n //Excluding repeating weight\n for(int i=1;i<=26;i++){\n mx=max(mx,weight[x][i]+weight[y][i]-2*weight[l][i]);\n }\n ans.push_back(len-mx);\n}\n\n return ans; \n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Tree', 'Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ | Binary Lifting | c-binary-lifting-by-anujjadhav-zmwh | Approach\nHere we are using Binary Lifting algo.\n Describe your approach to solving the problem. \nYou can learn about more such algo here: different-ways-to-f | AnujJadhav | NORMAL | 2023-09-06T06:12:12.846518+00:00 | 2023-09-06T06:12:12.846551+00:00 | 24 | false | # Approach\nHere we are using Binary Lifting algo.\n<!-- Describe your approach to solving the problem. -->\nYou can learn about more such algo here: [different-ways-to-find-lca-simplified](https://leetcode.com/discuss/study-guide/4005809/different-ways-to-find-lca-simplified)\n\n# Complexity\n- Time complexity: $$O(q * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n * log(n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n\n int n, l;\n vector<vector<pair<int, int>>> adj; // u -> v, wt\n vector<pair<int, int>> parent; // u -> parent v, wt (u -> v wt)\n vector<int> depth; // depth of the node\n vector<vector<int>> up;\n vector<vector<vector<int>>> sum;\n\n void dfs(int u) {\n for(auto it: adj[u]) {\n int child = it.first, wt = it.second;\n if(child == parent[u].first) continue;\n parent[child] = {u, wt};\n depth[child] = 1 + depth[u];\n dfs(child);\n }\n }\n\n void build() {\n this->l = ceil(log2(n));\n up = vector<vector<int>>(n, vector<int>(l + 1));\n sum = vector<vector<vector<int>>>(n, vector<vector<int>>(l + 1, vector<int>(26)));\n\n for(int u = 1; u < n; u++) {\n up[u][0] = parent[u].first;\n sum[u][0][parent[u].second - 1]++;\n }\n\n for(int i = 1; i <= l; i++)\n for(int u = 0; u < n; u++) {\n int parent = up[u][i-1];\n for(int wt = 0; wt < 26; wt++)\n sum[u][i][wt] = sum[u][i-1][wt] + sum[parent][i-1][wt];\n up[u][i] = up[parent][i-1];\n }\n }\n\n void pre() {\n depth = vector<int>(n);\n parent = vector<pair<int, int>>(n);\n dfs(0);\n build();\n }\n\n pair<int, vector<int>> query(int u, int jump) {\n vector<int> res(26);\n for(int i = l; i >= 0; i--)\n if(jump & (1 << i)) {\n for(int wt = 0; wt < 26; wt++)\n res[wt] += sum[u][i][wt];\n u = up[u][i];\n }\n return {u, res};\n }\n\n vector<int> getLCA(int u, int v) {\n vector<int> res(26);\n\n if(depth[u] < depth[v]) \n swap(u, v);\n\n int diff = depth[u] - depth[v];\n auto val = query(u, diff);\n u = val.first, res = val.second;\n\n if(u == v) return res;\n\n for(int i = l; i >= 0; i--) {\n int newu = up[u][i];\n int newv = up[v][i];\n\n if(newu == newv) continue;\n \n for(int wt = 0; wt < 26; wt++)\n res[wt] += sum[u][i][wt] + sum[v][i][wt];\n \n u = newu;\n v = newv;\n }\n\n for(int wt = 0; wt < 26; wt++)\n res[wt] += sum[u][0][wt] + sum[v][0][wt];\n \n return res;\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n this->n = n;\n adj = vector<vector<pair<int, int>>>(n);\n for(auto edge: edges) {\n int u = edge[0], v = edge[1], wt = edge[2];\n adj[u].push_back({v, wt});\n adj[v].push_back({u, wt});\n }\n\n pre();\n\n vector<int> res;\n\n for(auto quer: queries) {\n int u = quer[0], v = quer[1];\n vector<int> wt = getLCA(u, v);\n int sum = accumulate(wt.begin(), wt.end(), 0);\n int max = *max_element(wt.begin(), wt.end());\n res.push_back(sum - max);\n }\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ solution using binary lifting and dfs | c-solution-using-binary-lifting-and-dfs-u5du4 | Code\n\nclass Solution {\n vector<pair<int,int>> g[10001];\n int LOG;\n vector<vector<int>> up;\n vector<vector<int>> weights;\n vector<int> dept | ishanjoshiian | NORMAL | 2023-09-05T08:58:58.628118+00:00 | 2023-09-05T08:58:58.628145+00:00 | 8 | false | # Code\n```\nclass Solution {\n vector<pair<int,int>> g[10001];\n int LOG;\n vector<vector<int>> up;\n vector<vector<int>> weights;\n vector<int> depth;\npublic:\n void dfs(int v, int par, vector<int>& wt) {\n weights[v] = wt;\n up[v][0] = par;\n for(int j=1; j<LOG; ++j) {\n up[v][j] = up[ up[v][j-1] ][j-1];\n }\n for(auto it: g[v]) {\n int child_v = it.first;\n if(child_v == par) continue;\n depth[child_v] = depth[v]+1;\n int child_wt = it.second;\n wt[child_wt]++;\n dfs(child_v, v, wt);\n wt[child_wt]--;\n }\n }\n \n int get_lca(int a, int b) {\n if(depth[a] < depth[b]) swap(a, b);\n int k = depth[a] - depth[b];\n for(int j=0; j<LOG; ++j) {\n if((k>>j)&1) {\n a = up[a][j];\n }\n }\n \n if(a == b) return a;\n \n for(int j=LOG-1; j>=0; --j) {\n if(up[a][j] != up[b][j]) {\n a = up[a][j];\n b = up[b][j];\n }\n }\n \n return up[a][0];\n }\n \n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n LOG = 0;\n while((1<<LOG) <= n) LOG++;\n for(int i=0; i<edges.size(); ++i) {\n int u = edges[i][0], v = edges[i][1], wt = edges[i][2];\n g[u].push_back({v, wt});\n g[v].push_back({u, wt});\n }\n \n vector<int> wt(27, 0);\n up = vector<vector<int>>(n, vector<int>(LOG));\n depth = vector<int>(n, 0);\n weights = vector<vector<int>>(n);\n dfs(0, 0, wt);\n \n vector<int> ans;\n for(int i=0; i<queries.size(); ++i) {\n int a = queries[i][0], b = queries[i][1];\n int lca = get_lca(a, b);\n int mx_frq = 0, total = 0;\n for(int i=0; i<27; ++i) {\n int wt_count = weights[a][i] + weights[b][i] - 2*weights[lca][i];\n mx_frq = max(mx_frq, wt_count);\n total += wt_count;\n }\n ans.push_back(total-mx_frq);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Neat implementation of Binary lifting | neat-implementation-of-binary-lifting-by-useq | Intuition\nFind LCA and as the weights is till 26 store an array of size 26 for each node which tells you the freq of each element from root to that node\n\n# A | Jayachandra_r_k | NORMAL | 2023-09-05T07:12:38.775572+00:00 | 2023-09-05T07:12:38.775592+00:00 | 18 | false | # Intuition\nFind LCA and as the weights is till 26 store an array of size 26 for each node which tells you the freq of each element from root to that node\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nnlogn\n\n- Space complexity:\nnlogn\n\n# Code\n```\nclass Solution {\npublic:\n #define pii pair<int,int>\n #define F first\n #define S second\n #define MP make_pair\n vector<vector<int>>arr;\n vector<vector<int>>par;\n vector<int>depth;\n vector<vector<pii>>g;\n void dfs(int node,int pp,int val,int dd){\n arr[node]=arr[pp];\n depth[node]=dd;\n arr[node][val]++;\n par[node][0]=pp;\n for(int i=1;i<=20;i++){\n par[node][i]=par[par[node][i-1]][i-1];\n }\n \n for(auto x:g[node]){\n int v=x.F;\n int nval=x.S;\n if(v!=pp){\n dfs(v,node,nval,dd+1);\n }\n }\n \n \n }\n \n int LCA(int u,int v){\n if(depth[u]<depth[v])swap(u,v);\n \n for(int i=20;i>=0;i--){\n if(((depth[u]-depth[v])&(1LL<<i))){\n u=par[u][i];\n }\n }\n \n if(u==v)return u;\n int x=depth[v];\n for(int i=20;i>=0;i--){\n if(par[u][i]!=par[v][i]){\n u=par[u][i];\n v=par[v][i];\n } \n }\n return par[u][0];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n \n g.resize(n+1);\n depth.resize(n+1);\n par.assign(n+1,vector<int>(22,0));\n arr.assign(n+1,vector<int>(30,0));\n for(auto x:edges){\n int u=x[0]+1;\n int v=x[1]+1;\n g[u].push_back(MP(v,x[2]));\n g[v].push_back(MP(u,x[2]));\n }\n \n dfs(1,0,0,0);\n vector<int>ans;\n // cout<<LCA(6,7)<<endl;\n for(int i=0;i<queries.size();i++){\n int u=queries[i][0]+1;\n int v=queries[i][1]+1;\n int lc=LCA(u,v);\n \n int sum=0,maxi=0;\n for(int i=1;i<30;i++){\n int x=arr[v][i]+arr[u][i]-2*arr[lc][i];\n sum+=x;\n maxi=max(maxi,x);\n }\n \n ans.push_back(sum-maxi);\n \n }\n \n return ans;\n \n \n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Depth-First Search', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA using BinaryLifting in Java | lca-using-binarylifting-in-java-by-rahul-bi30 | Approach\nUtilized binary lifting to find LCA in O(logn) time and also kept the track of paths for each node to determine the final answer for each query.\n\n# | rahul_7011 | NORMAL | 2023-09-04T14:47:53.529388+00:00 | 2023-09-04T14:47:53.529407+00:00 | 22 | false | # Approach\nUtilized binary lifting to find LCA in O(logn) time and also kept the track of paths for each node to determine the final answer for each query.\n\n# Complexity\n- Time complexity:\nn:Total no. of nodes\nm:Total no. of queries\nPreComputing: 2D DP for binary lifting is O(nlogn).\nFor each query it takes O(logn) to find LCA and for calculating current query answer it takes O(26) = O(1).\nFor all queries total O(mlogn).\nTotal Time Complexity => O(nlogn + mlogn).\n\n\n# Code\n```\nclass Solution {\n public static class Edge {\n int v, w;\n\n Edge(int v, int w) {\n this.v = v;\n this.w = w;\n }\n }\n HashMap<Integer,int[]>tracks;\n private void getTracks(ArrayList<Edge>[] graph,int src,int par,int[] currTrack)\n {\n for(int i=0;i<currTrack.length;i++)\n {\n int[] store=tracks.get(src);\n store[i]=currTrack[i];\n }\n for(Edge e:graph[src])\n {\n if(e.v!=par)\n {\n currTrack[e.w]+=1;\n getTracks(graph,e.v,src,currTrack);\n currTrack[e.w]-=1;\n }\n }\n }\n private void getDepth(ArrayList<Edge>[] graph,int currDepth,int src,int par,HashMap<Integer,Integer>depth)\n {\n depth.put(src,currDepth);\n for(Edge e:graph[src])\n {\n if(e.v!=par)\n {\n getDepth(graph,currDepth+1,e.v,src,depth);\n }\n }\n }\n //up[node][2^i level]\n private void bLifting(ArrayList<Edge>[] graph,int src,int par,int[][] up) {\n up[src][0]=par;\n for(int i=1;i<17;i++)\n {\n if(up[src][i-1]!=-1)\n {\n up[src][i]=up[(up[src][i-1])][i-1];\n }else{\n up[src][i]=-1;\n }\n }\n for(Edge e:graph[src])\n {\n if(e.v!=par)\n {\n bLifting(graph,e.v,src,up);\n }\n }\n }\n private int makeLevelSame(ArrayList<Edge>[] graph,int src,int k,int[][] up)\n {\n if (k == 0) {\n return src;\n }\n for(int i=16;i>=0;i--)\n {\n int mask=(1<<i);\n if ((mask & k) != 0) {\n return makeLevelSame(graph,up[src][i], k - mask, up);\n }\n }\n return -1;\n }\n private int[] LCAusingBLifting(ArrayList<Edge>[] graph,int p,int q,int[][]up)\n {\n if(p==q)\n {\n return tracks.get(p);\n }\n //if parents are same then we have got the LCA\n if(up[p][0]==up[q][0])\n {\n return tracks.get(up[p][0]);\n }\n for(int i=16;i>=0;i--)\n {\n if (up[p][i]!=up[q][i]) {\n return LCAusingBLifting(graph,up[p][i],up[q][i],up);\n }\n }\n return new int[]{};\n }\n // n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]]\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n ArrayList<Edge>[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n graph[i] = new ArrayList<>();\n }\n for(int[]e:edges)\n {\n int u=e[0];\n int v=e[1];\n int w=e[2];\n graph[u].add(new Edge(v,w));\n graph[v].add(new Edge(u,w));\n }\n //Calculate track for node\n tracks=new HashMap<>();\n for(int i=0;i<=n;i++)\n {\n tracks.put(i,new int[26+3]);\n }\n getTracks(graph,0,-1,new int[26+3]);\n\n //Lowest Common Ancestor\n HashMap<Integer,Integer>depth=new HashMap<>();\n getDepth(graph,0,0,-1,depth);\n //There are 10^5 nodes that means log2(10^4) ~= 14 => 14+3 => 17\n int[][]up=new int[(int)1e4+3][14+3];\n bLifting(graph,0,-1,up);\n\n int k=0;\n int[] ans=new int[queries.length];\n for(int[]x:queries)\n {\n int p=x[0];\n int q=x[1];\n\n int depthP=depth.get(p);\n int depthQ=depth.get(q);\n //Now we need to make sure that they are on the same depth\n int[]pTrack=tracks.get(p);\n int[]qTrack=tracks.get(q);\n if(depthP<depthQ)\n {\n q=makeLevelSame(graph,q,depthQ-depthP,up);\n }else{\n p=makeLevelSame(graph,p,depthP-depthQ,up);\n }\n //Now they are on same depth\n int[] lcaTrack=LCAusingBLifting(graph,p,q,up);\n int cnt=0;\n int max=0;\n int sum=0;\n for(int i=0;i<pTrack.length;i++)\n {\n max=Math.max(max,pTrack[i]+qTrack[i]-2*lcaTrack[i]);\n sum+=pTrack[i]+qTrack[i]-2*lcaTrack[i];\n }\n cnt=(sum-max);\n ans[k++]=cnt;\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA USING BINARY LIFITING O(QLOGN) | lca-using-binary-lifiting-oqlogn-by-ksbu-qo24 | \n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(QLOG N)+O(N LOG N)\n\n- Space complexity:\n Add your space complexity here, e. | ksbu_2003 | NORMAL | 2023-09-04T10:59:38.383096+00:00 | 2023-09-04T10:59:38.383118+00:00 | 12 | false | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**O(Q*LOG N)+O(N* LOG N)**\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**O(N*27)**\n\n# Code\n```\nclass Solution {\npublic:\nvector<vector<int>>count;\n void dfs(int node,int par,vector<pair<int,int>>graph[],vector<int>&h,int x,vector<int>&v,vector<vector<int>>&sp,int mx)\n {\n count[node]=v;\n sp[node][0]=par;\n for(int i=1;i<=mx;i++)\n {\n sp[node][i]=sp[sp[node][i-1]][i-1];\n }\n h[node]=x;\n for(auto &it:graph[node])\n {\n if(it.first!=par)\n {\n v[it.second]++;\n dfs(it.first,node,graph,h,x+1,v,sp,mx);\n v[it.second]--;\n }\n }\n }\n int lca(int node1,int node2,vector<vector<int>>&sp,vector<int>&h,int mx)\n {\n if(h[node1]<h[node2])\n {\n swap(node1,node2);\n }\n for(int i=mx;i>=0;i--)\n {\n if(h[node1]-pow(2,i)>=h[node2])\n {\n node1=sp[node1][i];\n }\n }\n if(node1==node2) return node1;\n for(int i=mx;i>=0;i--)\n {\n if(sp[node1][i]!=sp[node2][i])\n {\n node1=sp[node1][i];\n node2=sp[node2][i];\n }\n }\n return sp[node1][0];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<int>par(n+1,n);\n vector<int>h(n+1,0);\n vector<int>v(27,0);\n count.resize(n+1,vector<int>(27,0));\n vector<pair<int,int>>graph[n+1];\n int mx=ceil(log2(n));\n vector<vector<int>>sp(n+1,vector<int>(mx+1,n));\n for(auto &it:edges)\n {\n graph[it[1]].push_back({it[0],it[2]});\n graph[it[0]].push_back({it[1],it[2]});\n }\n dfs(0,n,graph,h,0,v,sp,mx);\n vector<int>ans;\n for(auto &it:queries)\n {\n int y=lca(it[0],it[1],sp,h,mx);\n int mx=0,su=0;\n for(int i=1;i<=26;i++)\n {\n mx=max(mx,count[it[0]][i]+count[it[1]][i]-2*count[y][i]);\n su+=(count[it[0]][i]+count[it[1]][i]-2*count[y][i]);\n }\n ans.push_back(su-mx);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Java Offline LCA Tarjan O(26n+26m) | java-offline-lca-tarjan-o26n26m-by-reed_-5c4d | ```\n private int[] sln2(int n, int[][] edges, int[][] qs){\n //offline LCA\n int m = qs.length;\n int z = 26;\n List[] es = new | reed_w | NORMAL | 2023-09-04T06:15:09.934902+00:00 | 2023-09-04T06:15:09.934922+00:00 | 23 | false | ```\n private int[] sln2(int n, int[][] edges, int[][] qs){\n //offline LCA\n int m = qs.length;\n int z = 26;\n List<int[]>[] es = new List[n];\n for(int i = 0;i<n;i++) es[i] =new ArrayList<>();\n for(int[] e: edges){\n es[e[0]].add(new int[]{e[1],e[2]-1});\n es[e[1]].add(new int[]{e[0],e[2]-1});\n }\n \n List<Integer>[] queries = new List[n];\n for(int i = 0;i<n;i++) queries[i] = new ArrayList<>();\n for(int[] q: qs){\n queries[q[0]].add(q[1]);\n queries[q[1]].add(q[0]);\n }\n \n Map<Integer, Integer> lcaMap = new HashMap<>();\n int[][] cost = new int[n][z];\n int[] depth = new int[n];\n tarjan(0, es, depth, cost, new HashMap<>(), new boolean[n], queries, lcaMap);\n \n int[] res = new int[m];\n for(int i = 0;i<m;i++){\n int key = (qs[i][0]<<16) + qs[i][1];\n int lca = lcaMap.get(key);\n int total = depth[qs[i][0]]+depth[qs[i][1]]-2*depth[lca];\n res[i] = total;\n for(int j = 0;j<z;j++) {\n int count = cost[qs[i][0]][j]+cost[qs[i][1]][j]-2*cost[lca][j];\n res[i] = Math.min(res[i], total-count);\n }\n }\n return res;\n }\n \n private void tarjan(int curr, List<int[]>[] es, int[] depth, int[][] cost, Map<Integer,Integer> map, boolean[] visited, List<Integer>[] queries, Map<Integer, Integer> res){\n visited[curr] = true;\n for(int[] next: es[curr]){\n if(visited[next[0]]) continue;\n \n depth[next[0]] = depth[curr]+1;\n cost[next[0]] = cost[curr].clone();\n cost[next[0]][next[1]]++;\n \n tarjan(next[0], es, depth, cost, map, visited, queries, res);\n map.put(next[0], curr);\n }\n \n for(int secondKey: queries[curr]){\n if(visited[secondKey]){\n int lca = find(secondKey, map);\n res.put((curr<<16)+secondKey, lca);\n res.put((secondKey<<16)+curr, lca);\n }\n }\n }\n \n private Integer find(Integer u, Map<Integer,Integer> map){\n if(map.getOrDefault(u, u)==u) return u;\n map.put(u, find(map.get(u), map));\n return map.get(u);\n } | 0 | 0 | [] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Python3: Graph traversal using DFS and LCA using binary lifting | python3-graph-traversal-using-dfs-and-lc-9lt5 | Intuition\nWithout loss of generality, let\'s denote $n_0 = 0$ as the root. For each node $n_i$, we determine the frequency $F_i = [f_{i,0},...,f_{i,25}]$, wher | ChenxiLu | NORMAL | 2023-09-04T00:27:58.490531+00:00 | 2023-09-04T00:27:58.490560+00:00 | 26 | false | # Intuition\nWithout loss of generality, let\'s denote $n_0 = 0$ as the root. For each node $n_i$, we determine the frequency $F_i = [f_{i,0},...,f_{i,25}]$, where $f_{i, j}$ counts the number of edges with weight $j+1$ on the path from $n_0$ to $n_i$.\n\nThen for any pair of nodes $(n_p, n_q)$, if we determine that their lowest common ancestor (LCA) is $n_a$, then the frequency weights for the path connection $n_p, n_q$ is\n$$F = F_p + F_q - 2F_a = [f_{p, j}+f_{q, j}-2f_{a,j}, j = 0,...,25]$$. \n\nThe minimum number of operations needed for $(n_p, n_q)$ is thus\n$\\sum_{j=0}^{25}\\left(f_{p, j}+f_{q, j}-2f_{a,j}\\right) - \\max_{j=0}^{25}\\left\\{f_{p, j}+f_{q, j}-2f_{a,j}\\right\\}$.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize the problem to build the adjacency graph.\n2. Starting from root 0, traverse the graph using DFS to determine the parents, node levels, and edge frequencies for each node.\n3. For each pair of nodes, determine their LCA using binary lifting,\n4. Compute the minimum number of operations as illustrated above.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. $O(n)$ for graph traversal.\n2. $O(n\\log(n))$ for building the binary lifting.\n3. $O(M\\log(n))$ for finding the LCA for $M$ queries.\n4. $O(M)$ for computing the minimum number of operations for $M$ queries.\nTherefore, total complexity is $O\\left(\\max(M, n)\\log(n)\\right)$. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. $O(n\\log(n))$ for binary lifting\n2. $O(n)$ for the graph adjacency list\nTherefore, total complexity is $O(n\\log(n))$.\n\n# Code\n```\nclass Solution:\n def __init__(self):\n self.level = None # store the level of nodes\n self.adj = None # adjacency graph\n self.freq = None # frequency of edge weights from root (0) to the node\n self.tree = None # tree structure of the graph, can be optimized away\n self.visited = set() # set used to mark visited nodes in graph traversal\n # cache used to store jump parents of each node: \n # self.parent[i][j]: the parent of node j after 2^i jumps \n self.parent = None \n\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n self.initialize(n, edges)\n res = []\n for node1, node2 in queries:\n if self.level[node1] > self.level[node2]:\n ancestor = self.findLCA(node2, node1)\n else:\n ancestor = self.findLCA(node1, node2)\n total, _max = 0, 0\n for i in range(26):\n count = self.freq[node1][i] + self.freq[node2][i] - 2 * self.freq[ancestor][i]\n total += count\n _max = max(_max, count)\n res.append(total - _max)\n return res\n\n def initialize(self, n, edges):\n # initialization\n self.level = [0] * n\n # build adjacency graph\n self.adj = [[] for _ in range(n)]\n for n1, n2, wt in edges:\n self.adj[n1].append((n2, wt))\n self.adj[n2].append((n1, wt))\n self.freq = [None] * n\n self.freq[0] = [0 for _ in range(26)]\n self.tree = [-1] * n\n # graph traversal to populate frequencies, levels and parents\n self.traverse(-1, 0, 0)\n # prepare parent lists for binary lifting\n self.prepareLCA(n)\n\n # graph traversal\n def traverse(self, parent, node, level, weight = None):\n self.level[node] = level\n self.tree[node] = parent\n self.visited.add(node)\n if weight is not None:\n if self.freq[node] is None:\n self.freq[node] = self.freq[parent].copy()\n self.freq[node][weight-1] += 1\n for nb, wt in self.adj[node]:\n if nb not in self.visited:\n self.traverse(node, nb, level + 1, wt)\n\n # prepare data to find LCA using binary lifting\n def prepareLCA(self, n):\n # calculate N as the max number of jumps we need, could use log2(n)+1\n bits, count, _n = [], 0, n\n while _n != 0:\n bit = _n&1\n if bit == 1:\n bits.append(count)\n count += 1\n _n >>= 1\n N = bits[-1] + 1\n self.parent = [[-1] * n for _ in range(N)]\n self.parent[0] = self.tree.copy()\n for i in range(1, N):\n for j in range(n):\n jumpParent = self.parent[i-1][j]\n if jumpParent == -1:\n continue\n self.parent[i][j] = self.parent[i-1][jumpParent]\n \n def findLCA(self, node1, node2):\n # prereq: node2 is deeper than node1\n diff = self.level[node2] - self.level[node1]\n index = 0\n while diff != 0:\n if diff&1 == 1:\n node2 = self.parent[index][node2]\n index += 1\n diff >>= 1\n if node1 == node2:\n return node1\n N = len(self.parent)\n for i in range(N-1, -1, -1):\n if self.parent[i][node1] != self.parent[i][node2]:\n node1 = self.parent[i][node1]\n node2 = self.parent[i][node2]\n return self.parent[0][node1]\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | How to tackle this in a contest ! | how-to-tackle-this-in-a-contest-by-rishu-be98 | Pre-requisites\nLowest Common Ancestor of a given pair of nodes in O(logN) time. \n Describe your first thoughts on how to solve this problem. \n# Intuition \nQ | rishu_kr | NORMAL | 2023-09-03T23:36:31.159094+00:00 | 2023-09-03T23:39:03.066055+00:00 | 38 | false | # Pre-requisites\nLowest Common Ancestor of a given pair of nodes in O(logN) time. \n<!-- Describe your first thoughts on how to solve this problem. -->\n# Intuition \nQuery problem generally in a question of tree is related to LCA methodology, also if you would try bruteforce this, Then you can see for any qth query given node u and node v, the minimum change required is the **MIN(total_number of edges - number_of_edge_(i))** where i ranges from 1 to 26, considering all type of edges.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitially put all the edges in the tree (mp in code) and assume node 0 as the parent.\n\nDFS will iterate over all nodes and tells what is the parent of a given src, and subsequently updates the level of it\'s neighbour nodes. \n\nThen make the jump matrix, Note that jump[i][j] tells 2 power ith ancestor of node j, This you must know in LCA concept.\n\nThen write the liftNode and LCA finding functions, pretty much similar in any LCA problem. \n\nThen freq matrix was built using another DFS_2 I made an empty temp vector which stores the edge weights that has been occured reaching the source node from root, and at every recursive call all the elements in the temp was added to the frequency matrix. Don\'t forget the backtrack step where you pop in the temp. \n\nNow this freq[i][j] tells me to reach at node \'i\' from root number of \'i\' type of edge weights occured. \n\nThen for every query, find the total_edge b/w the given nodes, i.e,\ntotal_edge = lvl[a] - lvl[LCA] + lvl[b] - lvl[LCA].\nIterate over all 26 edge wts and find the number of changes needed to be made that is total_number of edges - number_of_edge_(i) and take minimum to obtain your answer.\n\nUpvote if you like my solution, More optimised solutions may present elsewhere. \n\n# Complexity\n- Time complexity:\nO(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(NlogN)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int freq[10005][27];\n int jump[19][10005];\n vector<int> parent;\n vector<int> lvl;\n map<int, vector<pair<int, int>> > mp; \n void dfs(int src, int par)\n {\n parent[src] = par;\n for(auto it : mp[src])\n {\n if(lvl[it.first] == -1 && it.first != par)\n {\n lvl[it.first] = 1 + lvl[src];\n dfs(it.first, src); \n }\n }\n }\n void dfs2(int src, vector<int> &temp, vector<vector<int>> &freq, int par)\n {\n for(int i = 0 ; i < temp.size() ; i++)\n freq[src][temp[i]]++;\n for(auto it : mp[src])\n {\n if(it.first != par)\n {\n temp.push_back(it.second);\n dfs2(it.first, temp, freq, src);\n temp.pop_back();\n }\n }\n }\n int liftNode(int node, int k)\n {\n if(node == -1 || k == 0) return node;\n int temp = node;\n for(int i = 18 ; i >= 0 ; i--)\n {\n if(k & (1<<i))\n {\n if(temp == -1) return temp;\n else temp = jump[i][temp];\n }\n }\n return temp;\n }\n int LCA(int a, int b)\n {\n if(lvl[a] < lvl[b])\n {\n return LCA(b, a);\n }\n a = liftNode(a, lvl[a] - lvl[b]);\n if(a == b) return a;\n for(int i = 18 ; i>=0 ; i--)\n {\n if(jump[i][a] != jump[i][b])\n {\n a = jump[i][a];\n b = jump[i][b];\n }\n }\n return parent[a];\n }\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {\n mp.clear();\n lvl.resize(n, -1);\n parent.resize(n);\n for(auto it : edges)\n {\n mp[it[0]].push_back({it[1], it[2]});\n mp[it[1]].push_back({it[0], it[2]});\n }\n lvl[0] = 0; // 0 as root \n dfs(0, -1);\n parent[0] = -1;\n memset(jump , -1, sizeof jump);\n for(int i = 0 ; i < n ; i++)\n {\n jump[0][i] = parent[i];\n }\n for(int i = 1 ; i < 19 ; i++)\n {\n for(int j = 0 ; j < n ; j++)\n {\n if(jump[i-1][j] == -1) jump[i][j] = -1;\n else jump[i][j] = jump[i-1][jump[i-1][j]];\n }\n } \n vector<vector<int>> freq(n, vector<int> (27, 0));\n vector<int> temp;\n vector<int> res;\n dfs2(0, temp, freq, -1);\n for(int q = 0 ; q < query.size(); q++){\n int a = query[q][0];\n int b = query[q][1];\n int ans = INT_MAX;\n int ancestor = LCA(a, b);\n int total_edge = lvl[a] + lvl[b] - 2*lvl[ancestor];\n for(int i = 1; i <= 26 ; i++)\n {\n ans = min(ans, total_edge - (freq[a][i] + freq[b][i] - 2*freq[ancestor][i]));\n }\n res.push_back(ans);\n } \n return res;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting for LCA | binary-lifting-for-lca-by-abhinav_1820-0i38 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Abhinav_1820 | NORMAL | 2023-09-03T19:13:30.293111+00:00 | 2023-09-03T19:13:30.293134+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int dp[28][10007];\n int par[10007][27];\n int depth[10007];\n void dfs(int i , int prev ,vector<pair<int, int>> v[]){\n par[i][0] = max(0 , prev);\n for(int j=1 ; j<=20 ; j++){\n par[i][j] = par[par[i][j-1]][j-1];\n }\n for(auto child : v[i]){\n if(child.first!=prev){\n for(int j=0 ; j<=26 ; j++){\n dp[j][child.first] = dp[j][i]+(child.second!=j);\n }\n depth[child.first] = depth[i]+1;\n dfs(child.first , i, v);\n }\n }\n }\n \n int lca(int u , int v){\n if(depth[u]<depth[v])\n swap(u , v);\n for(int i=20 ; i>=0 ; i--){\n if((depth[u]-depth[v])&(1<<i)){\n u = par[u][i];\n }\n }\n if(u==v)\n return u;\n \n for(int i=20 ; i>=0 ; i--){\n if(par[u][i]!=par[v][i]){\n u = par[u][i];\n v = par[v][i];\n }\n }\n return par[u][0];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n memset(dp , 0 , sizeof(dp));\n memset(par , 0 , sizeof(par));\n memset(depth , 0 , sizeof(depth));\n par[0][0]= 0;\n vector<pair<int , int>> v[n+1];\n for(int i=0 ; i<edges.size(); i++){\n v[edges[i][0]].push_back({edges[i][1], edges[i][2]});\n v[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n vector<int> ans(queries.size() , 0);\n dfs(0 , -1 , v);\n vector<int> ans1;\n for(int i=0 ; i<queries.size(); i++){\n int h = lca(queries[i][0] , queries[i][1]);\n int ans=1e9 , total=0;\n for(int ii=0 ; ii<=26; ii++){\n total += dp[ii][queries[i][0]]+dp[ii][queries[i][1]]- 2*dp[ii][h];\n ans = min(ans , dp[ii][queries[i][0]]+dp[ii][queries[i][1]]- 2*dp[ii][h]);\n }\n ans1.push_back(ans);\n }\n return ans1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | simple lca | simple-lca-by-ankitkumarhello20-6ti7 | ```\nclass Solution {\npublic:\n unordered_mapmp;\n void dfs(int u, vector>adj,vector&parent, vector>&num,vector&depth,int d=0){\n for(int i=1; | ankitkumarhello20 | NORMAL | 2023-09-03T19:01:26.880806+00:00 | 2023-09-03T19:01:26.880831+00:00 | 10 | false | ```\nclass Solution {\npublic:\n unordered_map<int,int>mp;\n void dfs(int u, vector<pair<int,int>>*adj,vector<int>&parent, vector<vector<int>>&num,vector<int>&depth,int d=0){\n for(int i=1;i<27;i++)\n num[u][i]=mp[i];\n for(auto [v,w]:adj[u]){\n if(v==parent[u]) continue;\n parent[v]=u;\n mp[w]++;\n dfs(v,adj,parent,num,depth,d+1);\n mp[w]--; //backtracking\n }\n depth[u]=d;\n return ;\n }\n int lca(int a, int b,vector<int>&depth,vector<int>&parent){\n while(depth[a]>depth[b]){\n a=parent[a];\n }\n while(depth[b]>depth[a]){\n b=parent[b];\n }\n if(a==b) return a;\n while(parent[a]!=parent[b]){\n a=parent[a];\n b=parent[b];\n }\n return parent[a];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<int>parent(n);\n vector<pair<int,int>>adj[n];\n parent[0]=-1;\n for(auto vec:edges){\n adj[vec[0]].push_back({vec[1],vec[2]});\n adj[vec[1]].push_back({vec[0],vec[2]});\n }\n vector<vector<int>>num(n,vector<int>(27));\n vector<int>depth(n);\n dfs(0,adj,parent,num,depth);\n vector<int>ans;\n for(auto vec:queries){\n int a, b; a=vec[0],b=vec[1];\n int l=lca(a,b,depth,parent);\n int temp=INT_MIN;\n int sum=0;\n for(int i=1;i<27;i++){\n int weqi=num[a][i]+num[b][i]-2*num[l][i];\n temp=max(temp,weqi);\n sum+=weqi;\n }\n \n \n ans.push_back(sum-temp);\n }\n return ans;\n }\n}; | 0 | 0 | [] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ LCA | c-lca-by-sae_young-nql2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sae_young | NORMAL | 2023-09-03T16:28:42.228319+00:00 | 2023-09-03T16:28:42.228349+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(Q * N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(max(E,N))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<pair<int,int>>> paths;\n int dst[10005] = {};\n int up[10005] = {};\n int memo[10005][27] = {{0,}};\n\n void init(vector<vector<int>>& edges, int n) {\n paths.resize(n);\n\n for(auto& edge : edges) {\n paths[edge[0]].push_back(make_pair(edge[1], edge[2]));\n paths[edge[1]].push_back(make_pair(edge[0], edge[2]));\n }\n\n for(int i=1; i<n; i++) dst[i] = -1;\n }\n\n void dfs(int node) {\n for(auto& [next, weight] : paths[node]) {\n if(dst[next] == -1) {\n dst[next] = dst[node] + 1;\n up[next] = node;\n for(int w=1; w<=26; w++) {\n memo[next][w] = memo[node][w] + (w == weight);\n }\n dfs(next);\n }\n }\n }\n\n int fca(int a, int b) {\n int diff = max(dst[a], dst[b]) - min(dst[a], dst[b]);\n \n while(diff--) {\n if(dst[a] > dst[b]) a = up[a];\n else b = up[b];\n } \n\n int d = dst[a];\n\n while(a != b) {\n a = up[a];\n b = up[b];\n }\n\n return a;\n }\n\n int solve(int a, int b) {\n int x = fca(a,b);\n\n int sum = 0;\n int maxCnt = 0;\n\n for(int w=1; w<=26; w++) {\n int diff = memo[b][w] + memo[a][w] - (memo[x][w] << 1);\n\n sum += diff;\n maxCnt = max(maxCnt, diff);\n }\n\n return sum - maxCnt;\n }\n\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n init(edges, n);\n\n dfs(0);\n\n vector<int> ans;\n\n for(auto& query : queries) {\n ans.push_back(solve(query[0], query[1]));\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ - O(nlogn) Solution with LCA(Binary-Lifting) and DP | c-onlogn-solution-with-lcabinary-lifting-0scg | Intuition\nAs there are queries in a tree-graph, it becomes clear that binary lifting will be used.\n\n# Approach\nBinary lifting and prefix sum counting, pleas | harshit_22f | NORMAL | 2023-09-03T15:31:33.651543+00:00 | 2023-09-03T16:49:39.980662+00:00 | 25 | false | # Intuition\nAs there are queries in a tree-graph, it becomes clear that binary lifting will be used.\n\n# Approach\nBinary lifting and prefix sum counting, please refer to code for step by step explanation.\n\n# Complexity\n- Time complexity:\nO((n+q)logn)\n\n- Space complexity:\nO(nlogn)\n\n# Code\n```\nclass Solution {\npublic:\n #define ll long long\n ll lca(ll u, ll v, vector<vector<ll>> &jump,vector<ll> &lev,ll mxb)\n {\n if(lev[u]>lev[v])swap(u,v);\n ll dif=lev[v]-lev[u];\n // first bringing nodes to same level\n for(int i=mxb-1;i>=0;i--)\n {\n if((1ll<<i)<=dif)\n {\n dif-=(1ll<<i);\n v=jump[i][v];\n }\n }\n if(u==v)return u;\n // now taking jumps simultaneously from both sides till the parents are not equal\n for(int i=mxb-1;i>=0;i--)\n {\n ll vp=jump[i][v],up=jump[i][u];\n if(vp!=up)\n {\n v=vp,u=up;\n }\n }\n return jump[0][v];\n }\n void dfs(ll node, ll pare, ll leve,vector<pair<ll,ll>> adj[],vector<ll>&par,vector<ll>&lev,vector<vector<ll>>&pre)\n {\n par[node]=pare;\n lev[node]=leve;\n for(auto &it:adj[node])\n {\n if(it.first!=pare)\n {\n pre[it.first]=pre[node];\n pre[it.first][it.second]++;\n dfs(it.first,node,leve+1,adj,par,lev,pre);\n }\n }\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& B) {\n vector<pair<ll,ll>> adj[n];\n for(auto &it:edges)\n {\n adj[it[0]].push_back({it[1],it[2]});\n adj[it[1]].push_back({it[0],it[2]});\n }\n // let 0 be the root;\n // BUILDING PREF SUM, PAR, RANK\n vector<vector<ll>>pre(n,vector<ll>(27,0));\n // pre consists of count of ith weight from root to given node\n vector<ll> par(n),rank(n);\n dfs(0,0,0,adj,par,rank,pre);\n ll mxb=0;\n // (1ll<<mxb) is the maximum jump we can take in a graph of n nodes\n ll m=n;\n while(m>0)\n {\n mxb++;\n m/=2;\n }\n vector<vector<ll>> jump(mxb,vector<ll>(n));\n // bulding kth ancestor\n jump[0]=par;\n \n for(int i=1;i<mxb;i++)\n {\n for(int j=0;j<n;j++)\n {\n ll pnt=jump[i-1][j];\n jump[i][j]=jump[i-1][pnt];\n }\n }\n vector<int> ans;\n for(auto &it:B)\n {\n ll u=it[0], v=it[1];\n ll x=lca(u,v,jump,rank,mxb);// by binary lifting\n // tot is total edges in path b/w u and v\n ll tot=rank[u]+rank[v]-2*rank[x];\n ll a=0;\n for(int i=0;i<=26;i++)\n {\n a=max(a,pre[u][i]+pre[v][i]-2*pre[x][i]);\n }\n // a is total edges in path b/w u and v with value having max frequency\n ans.push_back(tot-a);\n \n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Graph', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ LCA-Binary Lifting from cp-algorithms | c-lca-binary-lifting-from-cp-algorithms-3emzp | Intuition\n Describe your first thoughts on how to solve this problem. \nThis C++ solution is an enhanced version of standard online LCA-Binaer Lifting solution | xiaoping3418 | NORMAL | 2023-09-03T12:20:56.741911+00:00 | 2023-09-03T12:51:39.873971+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis C++ solution is an enhanced version of standard online LCA-Binaer Lifting solution: from https://cp-algorithms.com/graph/lca_binary_lifting.html\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n vector<vector<pair<int, int>>> graph;\n vector<vector<int>> up;\n vector<int> tin, tout;\n vector<unordered_map<int, int>> data;\n int timer = 0, l = 1;\n \n void dfs(int v, int p, unordered_map<int, int> &mp) {\n data[v] = mp;\n tin[v] = ++timer;\n up[v][0] = p;\n for (int i = 1; i <= l; ++i) {\n up[v][i] = up[up[v][i - 1]][i - 1];\n }\n\n for (auto[u, w] : graph[v]) {\n if (u == p) continue;\n ++mp[w];\n dfs(u, v, mp);\n --mp[w];\n }\n\n tout[v] = ++timer;\n }\n \n bool is_ancestor(int u, int v) {\n return tin[u] <= tin[v] && tout[u] >= tout[v];\n }\n\n int lca(int u, int v) { \n if (is_ancestor(u, v)) return u;\n if (is_ancestor(v, u)) return v;\n for (int i = l; i >= 0; --i) {\n if (not is_ancestor(up[u][i], v)) u = up[u][i];\n }\n return up[u][0];\n }\n \npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n graph.resize(n);\n for (auto &edge: edges) {\n int u = edge[0], v = edge[1], w = edge[2];\n graph[u].push_back({v, w});\n graph[v].push_back({u, w});\n }\n \n while ((1 << l) < n) l += 1;\n up.resize(n, vector<int>(l + 1)); \n data.resize(n);\n tin.resize(n);\n tout.resize(n);\n \n unordered_map<int, int> mp;\n dfs(0, 0, mp);\n vector<int> ret;\n \n for (auto q: queries) {\n int p = lca(q[0], q[1]);\n unordered_map<int, int> temp = data[q[0]];\n for (auto &it: data[q[1]]) temp[it.first] += it.second;\n for (auto &it: data[p]) temp[it.first] -= 2 * it.second;\n \n int sum = 0, mx = 0;\n for (auto &it: temp) {\n sum += it.second;\n mx = max(mx, it.second);\n }\n ret.push_back(sum - mx);\n }\n \n return ret;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | commented || LCA+DFS+BINARY LFITING (TO FIND LCS) | commented-lcadfsbinary-lfiting-to-find-l-dolu | \n\n# Code\n\n// Define a pair of integers as "pii" for convenience.\n#define pii pair<int, int>\n// Define shortcuts for the "first" and "second" elements of a | Aasmaan_Vs_Aasmaan | NORMAL | 2023-09-03T11:03:43.601770+00:00 | 2023-09-03T11:03:43.601800+00:00 | 24 | false | \n\n# Code\n```\n// Define a pair of integers as "pii" for convenience.\n#define pii pair<int, int>\n// Define shortcuts for the "first" and "second" elements of a pair.\n#define F first\n#define S second\n\n// Constants for the problem.\nconst int N = 1e4 + 1; // Maximum number of nodes.\nconst int W = 27; // Maximum weight.\n\n// 2D vectors to store information about parents, frequency, and levels of nodes.\nvector<vector<int>> par(15, vector<int>(N, 0)); // Stores ancestor nodes.\nvector<vector<int>> frq(N, vector<int>(W, 0)); // Stores frequency of weights.\nvector<int> lvl(N, 0); // Stores levels of nodes.\nvector<vector<pii>> g(N); // Adjacency list representation of the graph.\n\n// Define a class called "Solution" for solving the problem.\nclass Solution {\n // Private member functions for the Solution class.\n void Reset() {\n // Reset various data structures to their initial state.\n for (auto &i : lvl) i = 0;\n for (auto &i : par)\n for (auto &j : i) j = 0;\n for (auto &i : g)\n i.clear();\n }\n\n void Dfs(int src, int parent) {\n // Perform a depth-first search on the graph to compute levels and ancestor nodes.\n\n // Update the level of the current node.\n lvl[src] = lvl[parent] + 1;\n\n // Compute ancestor nodes up to a depth of 15.\n par[0][src] = parent;\n for (int j = 1; j < 15; j++)\n par[j][src] = par[j - 1][par[j - 1][src]];\n\n // Recursively visit child nodes.\n for (auto child : g[src]) {\n if (child.F == parent) continue;\n\n // Update frequency of weights for the child node.\n frq[child.F] = frq[src];\n frq[child.F][child.S]++;\n\n // Recursive call to visit the child node.\n Dfs(child.F, src);\n }\n }\n\n int LCA(int u, int v) {\n // Find the Lowest Common Ancestor (LCA) of two nodes u and v.\n\n if (lvl[u] > lvl[v]) swap(u, v);\n\n int diff = lvl[v] - lvl[u];\n\n // Compute the LCA using binary lifting.\n for (int j = 0; j < 15; j++) {\n if (diff & (1 << j)) v = par[j][v];\n }\n\n if (u == v) return u;\n\n // Move up the tree to find the LCA.\n for (int j = 14; j >= 0; j--)\n if (par[j][u] != par[j][v]) {\n u = par[j][u];\n v = par[j][v];\n }\n\n return par[0][u];\n }\n\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>> &edges, vector<vector<int>> &queries) {\n // Public function to solve the problem.\n\n // Reset data structures for each test case.\n Reset();\n\n // Build the graph using the given edges and weights.\n for (auto i : edges) {\n g[i[0] + 1].push_back({i[1] + 1, i[2]});\n g[i[1] + 1].push_back({i[0] + 1, i[2]});\n }\n\n // Compute levels and ancestor nodes using depth-first search.\n Dfs(1, 0);\n\n // Initialize a vector to store results.\n vector<int> result;\n\n // Process each query.\n for (auto q : queries) {\n int u = q[0] + 1;\n int v = q[1] + 1;\n\n // Find the Lowest Common Ancestor of u and v.\n int lca = LCA(u, v);\n\n // Compute the frequency of weights for the nodes u and v.\n vector<int> f(W, 0);\n for (int j = 0; j < W; j++)\n f[j] = frq[u][j] + frq[v][j] - 2 * frq[lca][j];\n\n int mx = 0, sum = 0;\n\n // Find the maximum frequency and calculate the sum of frequencies.\n for (auto i : f) {\n mx = max(mx, i);\n sum += i;\n }\n\n // Add the result for this query to the result vector.\n result.push_back(sum - mx);\n }\n\n // Return the vector of results for all queries.\n return result;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Binary Lifting | binary-lifting-by-raj_tirtha-fcjo | Code\n\nclass Solution {\npublic:\n vector<int> parent;\n vector<int> level;\n vector<int> vis;\n vector<vector<int>> table;\n int h;\n vector | raj_tirtha | NORMAL | 2023-09-03T10:35:37.313186+00:00 | 2023-09-03T10:35:37.313212+00:00 | 12 | false | # Code\n```\nclass Solution {\npublic:\n vector<int> parent;\n vector<int> level;\n vector<int> vis;\n vector<vector<int>> table;\n int h;\n vector<vector<int>> dp;\n vector<vector<pair<int,int>>> adj;\n vector<int> ans;\n void dfs(int node,int l){\n vis[node]=1;\n level[node]=l;\n for(auto it:adj[node]){\n if(vis[it.first]==0){\n parent[it.first]=node;\n for(int j=1;j<=26;j++){\n dp[it.first][j]+=dp[node][j];\n }\n dp[it.first][it.second]++;\n dfs(it.first,l+1);\n }\n }\n }\n int func(int u,int v){\n int x=u,y=v,z=u;\n if(level[u]>level[v]) return func(v,u);\n int d=level[v]-level[u];\n for(int i=0;i<h;i++){\n int mask=(1<<i);\n if(d & mask){\n v=table[i][v];\n }\n }\n if(u!=v){\n for(int i=h-1;i>=0;i--){\n int vp=table[i][v],up=table[i][u];\n if(vp!=up){\n v=vp;\n u=up;\n }\n }\n z=parent[u];\n }\n vector<int> temp(27,0);\n int sum=0;\n for(int i=1;i<=26;i++){\n temp[i]=dp[x][i]+dp[y][i]-2*dp[z][i];\n sum+=temp[i];\n }\n int ans=sum;\n for(int i=1;i<=26;i++){\n ans=min(ans,sum-temp[i]);\n }\n return ans;\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n parent.resize(n,0);\n level.resize(n);\n vis.resize(n,0);\n int m=n;\n while(m>0){\n h++;\n m/=2;\n }\n table.resize(h,vector<int>(n));\n dp.resize(n,vector<int>(27,0));\n adj.resize(n);\n for(int i=0;i<edges.size();i++){\n int u=edges[i][0],v=edges[i][1],w=edges[i][2];\n adj[u].push_back({v,w});\n adj[v].push_back({u,w});\n }\n dfs(0,1);\n for(int i=0;i<n;i++){\n table[0][i]=parent[i];\n }\n for(int i=1;i<h;i++){\n for(int j=0;j<n;j++){\n table[i][j]=table[i-1][table[i-1][j]];\n }\n }\n for(int i=0;i<queries.size();i++){\n int u=queries[i][0],v=queries[i][1];\n ans.push_back(func(u,v));\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | JS Solution - LCA | js-solution-lca-by-cutetn-tmdh | An LCA problem for a contest is pretty cruel btw \uD83E\uDEE0\n(this took me roughly 38 minutes...)\n\n# Complexity\n- Time complexity: O((n + query.length)logn | CuteTN | NORMAL | 2023-09-03T10:28:49.564230+00:00 | 2023-09-03T10:30:49.770893+00:00 | 12 | false | An LCA problem for a contest is pretty cruel btw \uD83E\uDEE0\n(this took me roughly 38 minutes...)\n\n# Complexity\n- Time complexity: $$O((n + query.length)logn)$$\n- Space complexity: $$O(nlogn)$$\n\n# Code\n```js\n/** @typedef {{ anc: { v: number, counters: number[] }[], adj: { v: number, w: number }[], h: number, v: number }} NodeInfo */\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar minOperationsQueries = function (n, edges, queries) {\n if (n == 1) return queries.map(() => 0);\n\n /** @type {NodeInfo[]} */\n const g = Array(n).fill(undefined);\n\n function addEdge(u, v, w) {\n if (g[u]) g[u].adj.push({ v, w });\n else\n g[u] = {\n v: u,\n adj: [{ v, w }],\n anc: [],\n };\n }\n for (let i = n - 2; i >= 0; i--) {\n let [u, v, w] = edges[i];\n w--;\n addEdge(u, v, w);\n addEdge(v, u, w);\n }\n\n function mergeCounters(c1, c2) {\n let res = new Uint16Array(26);\n for (let i = 0; i < 26; i++) {\n res[i] = c1[i] + c2[i];\n }\n return res;\n }\n\n function addCounters(c1, c2) {\n for (let i = 0; i < 26; i++) {\n c1[i] += c2[i];\n }\n }\n\n function buildParent(v, h, parent, w) {\n const gv = g[v];\n gv.h = h;\n let curr;\n let mergedCounters;\n\n if (parent != undefined) {\n mergedCounters = new Uint16Array(26);\n mergedCounters[w]++;\n curr = {\n v: parent,\n counters: mergedCounters,\n };\n\n gv.anc.push(curr);\n curr = g[parent].anc[0];\n }\n\n let i = 1;\n while (curr) {\n (mergedCounters = mergeCounters(mergedCounters, curr.counters)),\n gv.anc.push({\n v: curr.v,\n counters: mergedCounters,\n });\n curr = g[curr.v].anc[i];\n i++;\n }\n\n for (let { v: u, w } of gv.adj) {\n if (u != parent) buildParent(u, h+1, v, w);\n }\n }\n\n buildParent(0, 0);\n\n function getResFromCounter(c) {\n let sum = 0;\n let max = 0;\n for (let i = 0; i < 26; i++) {\n sum += c[i];\n max = Math.max(max, c[i]);\n }\n return sum - max;\n }\n\n function query(a, b) {\n if (a == b) return 0;\n\n const counters = new Uint16Array(26);\n\n let ga = g[a];\n let gb = g[b];\n\n if (ga.h < gb.h) [ga, gb] = [gb, ga];\n let i = ga.anc.length;\n while (ga.h > gb.h) {\n i--;\n let next = ga.anc[i];\n if (next != undefined && g[next.v].h >= gb.h) {\n addCounters(counters, next.counters);\n ga = g[next.v];\n }\n }\n\n if (ga.v == gb.v) return getResFromCounter(counters);\n\n i = ga.anc.length;\n while (i) {\n i--;\n let nextA = ga.anc[i];\n let nextB = gb.anc[i];\n if (nextA != undefined && nextB != undefined && nextA.v != nextB.v) {\n addCounters(counters, nextA.counters);\n addCounters(counters, nextB.counters);\n ga = g[nextA.v];\n gb = g[nextB.v];\n }\n }\n\n addCounters(counters, ga.anc[0].counters)\n addCounters(counters, gb.anc[0].counters)\n return getResFromCounter(counters);\n }\n\n return queries.map(q => query(q[0], q[1]))\n};\n``` | 0 | 0 | ['Tree', 'Counting', 'JavaScript'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++ Solution | Binary Lifting | c-solution-binary-lifting-by-arjit_07-s4kp | Intuition\n Describe your first thoughts on how to solve this problem. \nBefore proceeding to the solution I would like to suggest you to watch Errichto\'s vide | arjit_07 | NORMAL | 2023-09-03T10:17:15.463903+00:00 | 2023-09-03T10:17:15.463925+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBefore proceeding to the solution I would like to suggest you to watch Errichto\'s video on Kth ancestor and Lowest common ancestor.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is straight forward. You simply start from any node as root. In my case I\'ve choosen 0 as the root node. Maintain a hash on every node which stores the occurance of each wt in the path from root node to that node. To calculate the answer find LCA of the query nodes. Use this for(int j = 1; j < 27; j++) temp[j] = hash[queries[i][0]][j] + hash[queries[i][1]][j] - 2 * hash[anc][j];. We are substracting hash[anc][j] twice because these weights will bw in the path from root node to our LCA, which we don\'t want in our answer, also these weights will be included in both the path from root node to our query node, so we will be substract twice of hash[anc][j];\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int LOG = 20;\n vector<int> parent;\n vector<vector<pair<int,int>>> adj;\n vector<vector<int>> hash;\n vector<int> depth;\n vector<vector<int>> up;\n\n \n void dfs(int node, int par, int wt, int k){\n if(wt != 0) hash[node][wt]++;\n parent[node] = par;\n depth[node] = k;\n for(auto it : adj[node]){\n if(it.first != par){\n hash[it.first] = hash[node];\n dfs(it.first, node, it.second, k+1);\n }\n }\n }\n \n void binary_lifting(int n){\n for(int i = 0; i < n; i++) up[i][0] = parent[i];\n\n for(int j = 1; j < LOG; j++){\n for(int i = 0; i < n; i++){\n up[i][j] = up[up[i][j-1]][j-1];\n }\n }\n }\n \n int lca(int a, int b){\n if(depth[a] < depth[b]){\n swap(a,b);\n }\n\n int k = depth[a] - depth[b];\n for(int j = LOG - 1; j >= 0; j--){\n if(k & (1 << j)){\n a = up[a][j];\n }\n }\n if(a == b) return a;\n for(int j = LOG - 1; j >= 0; j--){\n if(up[a][j] != up[b][j]){\n a = up[a][j];\n b = up[b][j];\n }\n }\n return up[a][0];\n }\n \n \n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n \n adj = vector<vector<pair<int,int>>>(n);\n parent = vector<int>(n);\n hash = vector<vector<int>>(n,vector<int>(27,0));\n depth = vector<int>(n);\n up = vector<vector<int>>(n, vector<int>(LOG, -1));\n \n for(int i = 0; i < edges.size(); i++){\n adj[edges[i][0]].push_back({edges[i][1],edges[i][2]});\n adj[edges[i][1]].push_back({edges[i][0],edges[i][2]});\n }\n \n dfs(0,-1,0,0);\n parent[0] = 0;\n \n binary_lifting(n);\n\n int q = queries.size();\n vector<int> ans;\n \n for(int i = 0; i < q; i++){\n int anc = lca(queries[i][0], queries[i][1]);\n \n vector<int> temp(27,0);\n for(int j = 1; j < 27; j++) temp[j] = hash[queries[i][0]][j] + hash[queries[i][1]][j] - 2 * hash[anc][j];\n \n int total = 0, maxFreq = 0;\n for(int i = 1; i < 27; i++){\n total += temp[i];\n maxFreq = max(maxFreq, temp[i]);\n }\n \n ans.push_back(total - maxFreq);\n }\n return ans;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | My Solution | my-solution-by-hope_ma-nn7a | \n/**\n * Time Complexity: O((n + n_queries) * log(n))\n * Space Complexity: O(n * log(n))\n * where `n_queries` is the length of the vector `queries`\n */\ncla | hope_ma | NORMAL | 2023-09-03T09:51:21.828954+00:00 | 2023-09-03T11:29:05.726293+00:00 | 3 | false | ```\n/**\n * Time Complexity: O((n + n_queries) * log(n))\n * Space Complexity: O(n * log(n))\n * where `n_queries` is the length of the vector `queries`\n */\nclass Solution {\n private:\n static constexpr int invalid_parent = -1;\n \n public:\n vector<int> minOperationsQueries(const int n,\n const vector<vector<int>> &edges,\n const vector<vector<int>> &queries) {\n constexpr int root = 0;\n constexpr int node1_i = 0;\n constexpr int node2_i = 1;\n constexpr int weight_i = 2;\n \n /**\n * <0>: the node\n * <1>: the parent of the node `<0>`\n * <2>: `weight_to_count` on the path from root `root` to the node `<0>`\n * where `weight_to_count[relative_weight]` stands for the number of the weight `weight`\n * of the edges on the path from the root `root` to the node `<0>`,\n * `weight` = (`relative_weight` + `min_weight`)\n */\n using q_node_t = tuple<int, int, vector<int>>;\n \n vector<pair<int, int>> graph[n];\n int max_weight = numeric_limits<int>::min();\n int min_weight = numeric_limits<int>::max();\n for (const vector<int> &edge : edges) {\n const int node1 = edge[node1_i];\n const int node2 = edge[node2_i];\n const int weight = edge[weight_i];\n graph[node1].emplace_back(node2, weight);\n graph[node2].emplace_back(node1, weight);\n max_weight = max(max_weight, weight);\n min_weight = min(min_weight, weight);\n }\n const int weight_range = edges.empty() ? 1 : max_weight - min_weight + 1;\n\n vector<int> weight_to_counts[n];\n int depth = 0;\n int depths[n];\n memset(depths, 0, sizeof(depths));\n int parents[n];\n memset(parents, invalid_parent, sizeof(parents));\n queue<q_node_t> q({make_tuple(root, invalid_parent, vector<int>(weight_range))});\n for (; !q.empty(); ++depth) {\n for (size_t qs = q.size(); qs > 0; --qs) {\n auto &[node, parent, weight_to_count] = q.front();\n for (const auto [child, weight] : graph[node]) {\n if (child == parent) {\n continue;\n }\n \n const int relative_weight = weight - min_weight;\n ++weight_to_count[relative_weight];\n q.emplace(child, node, weight_to_count);\n --weight_to_count[relative_weight];\n }\n weight_to_counts[node] = move(weight_to_count);\n depths[node] = depth;\n parents[node] = parent;\n q.pop();\n }\n }\n --depth;\n const int bits = get_bits(depth);\n vector<vector<int>> ancestors(bits, vector<int>(n, invalid_parent));\n for (int bit = 0; bit < bits; ++bit) {\n for (int node = 0; node < n; ++node) {\n if (bit == 0) {\n ancestors[bit][node] = parents[node];\n } else {\n const int ancestor = ancestors[bit - 1][node];\n if (ancestor != invalid_parent) {\n ancestors[bit][node] = ancestors[bit - 1][ancestor];\n }\n }\n }\n }\n\n vector<int> ret;\n for (const vector<int> &query : queries) {\n const int node1 = query.front();\n const int node2 = query.back();\n if (node1 == node2) {\n ret.emplace_back(0);\n continue;\n }\n\n const int lca = get_lca(ancestors, depths, node1, node2);\n const vector<int> &weight_to_count_1 = weight_to_counts[node1];\n const vector<int> &weight_to_count_2 = weight_to_counts[node2];\n const vector<int> &weight_to_count_lca = weight_to_counts[lca];\n int total = 0;\n int max_count = 0;\n for (int weight = 0; weight < weight_range; ++weight) {\n const int count = weight_to_count_1[weight] + weight_to_count_2[weight] - 2 * weight_to_count_lca[weight];\n total += count;\n max_count = max(max_count, count);\n }\n ret.emplace_back(total - max_count);\n }\n return ret;\n }\n \n private:\n int get_bits(const int depth) {\n int ret = 0;\n for (int d = depth; d != 0; d >>= 1) {\n ++ret;\n }\n return ret;\n }\n \n int get_ancestor(const vector<vector<int>> &ancestors, const int node, const int distance) {\n int ret = node;\n for (int bit = 0, d = distance; d != 0 && ret != invalid_parent; ++bit, d >>= 1) {\n if ((d & 0b1) == 0b1) {\n ret = ancestors[bit][ret];\n }\n }\n return ret;\n }\n \n int get_lca(const vector<vector<int>> &ancestors, const int *depths, const int node1, const int node2) {\n const int depth1 = depths[node1];\n const int depth2 = depths[node2];\n const int min_depth = min(depth1, depth2);\n int ancestor1 = get_ancestor(ancestors, node1, depth1 - min_depth);\n int ancestor2 = get_ancestor(ancestors, node2, depth2 - min_depth);\n if (ancestor1 == ancestor2) {\n return ancestor1;\n }\n\n const int bits = static_cast<int>(ancestors.size());\n for (int bit = bits - 1; bit > -1; --bit) {\n const int next_ancestor1 = ancestors[bit][ancestor1];\n const int next_ancestor2 = ancestors[bit][ancestor2];\n if (next_ancestor1 != next_ancestor2) {\n ancestor1 = next_ancestor1;\n ancestor2 = next_ancestor2;\n }\n }\n return ancestors[0][ancestor1];\n }\n};\n``` | 0 | 0 | [] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Using Binary lifting | using-binary-lifting-by-51_king-ut7w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | 51_KING | NORMAL | 2023-09-03T09:42:27.284003+00:00 | 2023-09-03T09:42:27.284026+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int sprase[21][10001];\n int depth[10001];\n void preCompute(int curr,vector <vector<pair<int,int>>> &adj,int parent)\n {\n sprase[0][curr] = parent;\n for(int i=1;i<=20;i++)\n {\n int med_p = sprase[i-1][curr];\n if(med_p==-1)\n sprase[i][curr] = -1;\n else\n sprase[i][curr] = sprase[i-1][med_p];\n }\n for(auto &x:adj[curr])\n {\n if(parent!=x.first)\n preCompute(x.first,adj,curr);\n }\n }\n int levelUp(int u,int up)\n {\n for(int i=20;i>=0;i--)\n {\n if(up&(1<<i))\n u = sprase[i][u];\n }\n return u;\n }\n int lca(int u,int v)\n {\n if(depth[u]<depth[v]) swap(u,v);\n\n u = levelUp(u,depth[u]-depth[v]);\n if(u==v) return u;\n for(int i=20;i>=0;i--)\n {\n if(sprase[i][u]==sprase[i][v]) continue;\n u = sprase[i][u];\n v = sprase[i][v];\n }\n return sprase[0][u];\n }\n void dfs(int i,vector <vector<pair<int,int>>> &adj,vector <int> &visited,vector <vector<int>> &countFre,vector <int> curr,int d)\n {\n visited[i] = 1;\n depth[i] = d;\n for(auto &x:adj[i])\n {\n if(!visited[x.first])\n {\n curr[x.second]+=1;\n countFre[x.first] = curr;\n dfs(x.first,adj,visited,countFre,curr,d+1);\n curr[x.second]-=1;\n }\n }\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector <vector<int>> countFre(n,vector<int>(27,0));\n vector <int> visited(n,0);\n vector <vector<pair<int,int>>> adj(n);\n for(auto &x:edges)\n {\n adj[x[0]].push_back({x[1],x[2]});\n adj[x[1]].push_back({x[0],x[2]});\n }\n vector <int> curr(27,0);\n dfs(0,adj,visited,countFre,curr,0);\n preCompute(0,adj,-1);\n \n // for(auto &x:countFre)\n // {\n // for(auto &c:x)\n // cout<<c<<" ";\n // cout<<endl;}\n \n vector <int> ans;\n \n for(auto &x:queries)\n {\n int s = x[0];\n int d = x[1];\n int lc = lca(s,d);\n // cout<<s<<" "<<d<<" "<<lc<<endl;\n vector <int> counts(27,0);\n for(int i=0;i<27;i++)\n {\n // if(lc==-1)\n // counts[i]=countFre[s][i]+countFre[d][i];\n // else\n counts[i]=countFre[s][i]+countFre[d][i]-2*countFre[lc][i];\n }\n int maxx=0,sum=0;\n for(int i=0;i<27;i++)\n {\n // cout<<counts[i]<<" ";\n maxx = max(maxx,counts[i]);\n sum+=counts[i];\n }\n // cout<<endl;\n ans.push_back(sum-maxx);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Memoization', 'C++'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | Awesome solution | awesome-solution-by-ujjwal_bishnoi-gxqa | Code\n\nclass Solution:\n def minOperationsQueries(\n self, n: int, edges: List[List[int]], queries: List[List[int]]\n ) -> List[int]:\n g = | Ujjwal_Bishnoi | NORMAL | 2023-09-03T09:12:29.168773+00:00 | 2023-09-03T09:12:29.168793+00:00 | 22 | false | # Code\n```\nclass Solution:\n def minOperationsQueries(\n self, n: int, edges: List[List[int]], queries: List[List[int]]\n ) -> List[int]:\n g = [[] for _ in range(n)]\n for u, v, w in edges:\n g[u].append((v, w - 1))\n g[v].append((u, w - 1))\n q = Deque()\n q.append(0)\n par = [0] * n\n pw = [0] * n\n dep = [0] * n\n sum = [None for _ in range(n)]\n f = [[0] * 14 for _ in range(n)]\n sum[0] = [0] * 26\n while len(q):\n u = q.popleft()\n f[u][0] = par[u]\n for i in range(1, 14):\n f[u][i] = f[f[u][i - 1]][i - 1]\n for v, w in g[u]:\n if par[u] != v:\n par[v] = u\n sum[v] = sum[u].copy()\n sum[v][w] += 1\n dep[v] = dep[u] + 1\n q.append(v)\n ans = []\n for u, v in queries:\n x, y = u, v\n if dep[x] > dep[y]:\n x, y = y, x\n for i in reversed(range(14)):\n if dep[y] - dep[x] >= 1 << i:\n y = f[y][i]\n for i in reversed(range(14)):\n if f[x][i] != f[y][i]:\n x, y = f[x][i], f[y][i]\n if x != y:\n x = par[x]\n ans.append(\n dep[u]\n + dep[v]\n - 2 * dep[x]\n - max([sum[u][i] + sum[v][i] - 2 * sum[x][i] for i in range(26)])\n )\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | C++✅ || Easy || Binary Lifting | c-easy-binary-lifting-by-prinzeop-uptv | \nclass Solution {\nprivate:\n int dp[10001][27];\n vector<pair<int, int>> adj[10001];\n int lvl[10001];\n int up[10001][20];\n void binarylift(i | casperZz | NORMAL | 2023-09-03T06:43:38.053821+00:00 | 2023-09-03T06:43:38.053847+00:00 | 37 | false | ```\nclass Solution {\nprivate:\n int dp[10001][27];\n vector<pair<int, int>> adj[10001];\n int lvl[10001];\n int up[10001][20];\n void binarylift(int v, int par) {\n up[v][0] = par;\n for (int i = 1; i < 20; ++i) {\n if (up[v][i - 1] != -1) up[v][i] = up[up[v][i - 1]][i - 1];\n else up[v][i] = -1;\n }\n for (auto &e : adj[v]) {\n if (e.first != par) binarylift(e.first, v);\n }\n }\n int ans_query(int v, int k) {\n for (int i = 19; i >= 0; --i) {\n if (v == -1 || k == 0) break;\n if (k >= (1 << i)) {\n k -= (1 << i);\n v = up[v][i];\n }\n }\n return v;\n }\n void dfs(int v, int par, int lev) {\n lvl[v] = lev;\n for (auto &e : adj[v]) {\n if (e.first == par) continue;\n dfs(e.first, v, lev + 1);\n }\n }\n int LCA(int a, int b) {\n if (lvl[a] < lvl[b]) swap(a, b);\n int diff = lvl[a] - lvl[b];\n a = ans_query(a, diff);\n if (a == b) return a;\n for (int i = 19; i >= 0; --i) {\n if (up[a][i] != up[b][i]) {\n a = up[a][i];\n b = up[b][i];\n }\n }\n return ans_query(a, 1);\n }\n void dfs1(int v, int par){\n for(int i = 1; i<=26; ++i) dp[v][i] += dp[par][i];\n for(auto &e : adj[v]){\n if(e.first == par) continue;\n dp[e.first][e.second]++;\n dfs1(e.first, v);\n }\n }\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& e, vector<vector<int>>& q) {\n vector<int> ans;\n for(auto &x: e) {\n adj[x[0]].emplace_back(x[1],x[2]);\n adj[x[1]].emplace_back(x[0],x[2]);\n }\n binarylift(0, -1);\n dfs(0, -1, 0);\n dfs1(0, 0);\n for(auto &e : q){\n int a = e[0], b = e[1];\n int tot = 0, maxi = 0;\n for(int i = 1; i<=26; ++i){\n int x = dp[a][i] + dp[b][i] - 2 * dp[LCA(a, b)][i];\n maxi = max(maxi, x);\n tot+=x;\n }\n ans.push_back(tot - maxi);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | ✅✅100% Easy Solution✅ | 100-easy-solution-by-pratik8696-833f | \n#pragma GCC optimize("Ofast")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")\n#pragma GCC optimize("unroll-loops")\n#include <bit | pratik8696 | NORMAL | 2023-09-03T06:26:45.577186+00:00 | 2023-09-03T06:26:45.577211+00:00 | 33 | false | ```\n#pragma GCC optimize("Ofast")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")\n#pragma GCC optimize("unroll-loops")\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <complex>\n#include <queue>\n#include <set>\n#include <unordered_set>\n#include <list>\n#include <chrono>\n#include <random>\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <map>\n#include <unordered_map>\n#include <stack>\n#include <iomanip>\n#include <fstream>\n\nusing namespace std;\nusing namespace __gnu_pbds;\ntypedef long long ll;\n// use less_equal to make it multiset\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> p32;\ntypedef pair<ll, ll> p64;\ntypedef pair<double, double> pdd;\ntypedef vector<ll> v64;\ntypedef vector<int> v32;\ntypedef vector<vector<int>> vv32;\ntypedef vector<vector<ll>> vv64;\ntypedef vector<vector<p64>> vvp64;\ntypedef vector<p64> vp64;\ntypedef vector<p32> vp32;\ntypedef vector<pair<p64, ll>> vpp64;\ntypedef set<ll> s64;\ntypedef set<p64> sp64;\ntypedef multiset<ll> ms64;\ntypedef multiset<p64> msp64;\ntypedef map<ll, ll> m64;\ntypedef map<ll, v64> mv64;\ntypedef unordered_map<ll, v64> uv64;\ntypedef unordered_map<ll, ll> u64;\ntypedef unordered_map<p64, ll> up64;\ntypedef unordered_map<ll, vp64> uvp64;\ntypedef priority_queue<ll> pq64;\ntypedef priority_queue<ll, v64, greater<ll>> pqs64;\nconst int MOD = 1000000007;\ndouble eps = 1e-12;\n#define forn(i, n) for (ll i = 0; i < n; i++)\n#define forsn(i, s, e) for (ll i = s; i < e; i++)\n#define rforn(i, s) for (ll i = s; i >= 0; i--)\n#define rforsn(i, s, e) for (ll i = s; i >= e; i--)\nstruct custom_hash\n{\n static uint64_t splitmix64(uint64_t x)\n {\n x += 0x9e3779b97f4a7c15;\n x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n return x ^ (x >> 31);\n }\n\n size_t operator()(p64 x) const\n {\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n return splitmix64(x.first + FIXED_RANDOM) ^ splitmix64(x.second + FIXED_RANDOM);\n }\n size_t operator()(ll x) const\n {\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n return splitmix64(x + FIXED_RANDOM);\n }\n};\ntypedef gp_hash_table<ll, ll, custom_hash> fm64;\ntypedef gp_hash_table<p64, ll, custom_hash> fmp64;\n\n#define ln "\\n"\n#define mp make_pair\n#define ie insert\n#define pb push_back\n#define fi first\n#define se second\n#define INF 2e18\n#define fast_cin() \\\n ios_base::sync_with_stdio(false); \\\n cin.tie(NULL); \\\n cout.tie(NULL)\n#define all(x) (x).begin(), (x).end()\n#define al(arr, n) arr, arr + n\n#define sz(x) ((ll)(x).size())\n#define dbg(a) cout << a << endl;\n#define dbg2(a) cout << a << \' \';\nusing ld = long double;\nusing db = double;\nusing str = string;\n#define tcT template <class T\n#define tcTU tcT, class U\n#define tcTUU tcT, class... U\ntcT > void re(T &x)\n{\n cin >> x;\n}\ntcTUU > void re(T &t, U &...u)\n{\n re(t);\n re(u...);\n}\n\nll fastexpo(ll a, ll b)\n{\n if (b == 0)\n {\n return 1;\n }\n if (a == 0)\n {\n return 0;\n }\n ll y = fastexpo(a, b / 2);\n if (b % 2 == 0)\n {\n return y * y;\n }\n else\n {\n return a * y * y;\n }\n}\n\n\nvector<vector<int>> hsh(10001,vector<int>(28));\n\nvoid dfs(int v, v64 &vis, uvp64 &adj)\n{\n vis[v] = 1;\n for (auto t : adj[v])\n {\n auto child=t.first;\n auto wt=t.second;\n if (vis[child] == 0)\n {\n // uska child ko lao\n hsh[child][wt]++;\n for(int i=1;i<=26;i++)\n {\n hsh[child][i]+=hsh[v][i];\n }\n dfs(child, vis, adj);\n }\n }\n}\n\n\nvoid bfs(uvp64 &adj, v64 &dist, ll src,v64 &parent)\n{\n queue<ll> q;\n q.push(src);\n dist[src] = 0;\n parent[src] = src;\n while (!q.empty())\n {\n ll curr = q.front();\n q.pop();\n for (auto t : adj[curr])\n {\n auto child=t.first;\n auto wt=t.second;\n if (dist[child] > dist[curr] + 1)\n {\n dist[child] = dist[curr] + 1;\n q.push(child);\n parent[child]=curr;\n }\n }\n }\n}\n\nll lca(ll a,ll b,ll sparse[][30],v64 &lvl)\n{\n ll rem = lvl[a] - lvl[b];\n if (rem < 0)\n {\n swap(a, b);\n }\n ll steps = abs(rem);\n while (steps)\n {\n a = sparse[a][__lg(steps)];\n steps -= fastexpo(2, __lg(steps));\n }\n if (a == b)\n {\n return a;\n }\n else\n {\n for (ll i = 30 - 1; i >= 0; i--)\n {\n if (sparse[a][i] != sparse[b][i])\n {\n a = sparse[a][i];\n b = sparse[b][i];\n }\n }\n return sparse[a][0];\n }\n}\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n uvp64 adj;\n for(auto t:edges)\n {\n int u=t[0];\n int v=t[1];\n int wt=t[2];\n u++,v++;\n adj[u].pb({v,wt});\n adj[v].pb({u,wt});\n }\n forsn(i,1,n+1)\n {\n forn(j,28)\n {\n hsh[i][j]=0;\n }\n }\n v64 vis(n+1);\n dfs(1,vis,adj);\n v64 parent(n + 1, 0);\n ll sparse[n + 1][30];\n v64 lvl(n + 1, INF);\n bfs(adj, lvl, 1, parent);\n forsn(i, 1, n + 1)\n {\n sparse[i][0] = parent[i];\n }\n for (ll j = 1; j < 30; j++)\n {\n for (ll i = 1; i <= n; i++)\n {\n sparse[i][j] = sparse[sparse[i][j - 1]][j - 1];\n }\n }\n v32 res;\n for(auto t:queries)\n {\n int u=t[0];\n int v=t[1];\n u++,v++;\n int lc=lca(u,v,sparse,lvl);\n vector<int> c=hsh[lc];\n vector<int> a=hsh[u];\n vector<int> b=hsh[v];\n int sum=0,maxx=0;\n for(int i=1;i<=26;i++)\n {\n int cc=a[i]+b[i]-2*c[i];\n sum+=cc;\n maxx=max(maxx,cc);\n }\n res.push_back(sum-maxx);\n }\n return res;\n }\n};\n``` | 0 | 0 | ['Depth-First Search', 'Breadth-First Search', 'C'] | 0 |
minimum-edge-weight-equilibrium-queries-in-a-tree | LCA using binary lifting | C++ | beats 100 % by runtime | precise code with referrence | lca-using-binary-lifting-c-beats-100-by-e389t | Intuition\nA path from node u to v in a tree is always unique and passes through the lca or lowest common ancester of u and v. In this problem the number of dif | shadow_47 | NORMAL | 2023-09-03T06:25:35.147985+00:00 | 2023-09-03T06:31:55.516351+00:00 | 32 | false | # Intuition\nA path from node `u` to `v` in a tree is always unique and passes through the `lca` or lowest common ancester of `u` and `v`. In this problem the number of different types of weights in an edge is `26`. So we will always keep the weight which is most frequent in the path from `u` to `v` and change the rest to that weight. So the answer would be `len - mxf`, where `len` is number of edges in the path from `u` to `v` find this using levels of `lca`, `u` and `v` and `mxf` is frequency of most frequent edge weight.\n\n# Approach\nAssume node `1` as root of the tree. `dp` is used for binary lifting, `ps[u][e]` is the count of edges in the path from `root` to `u` with edge weight as `w` and `lvl[u]` is level of node `u` assuming node `1` as root. So length of path from `u` to `v` would be `lvl[u] + lvl[v] - 2 * lvl[lca]`, `lca` is lowest common ascester of node `u` and `v`, So for each edge weight find out it\'s frequency in the path from `u` to `v` using the same formula as above but on `ps` array. So the answer of the query would be,`lvl[u] + lvl[v] - 2 * lvl[lca] - max(ps[u][w] + ps[v][w] - 2 * ps[lca][w]`, over all possible values of `w` i.e. from `1` to `26`.\n\n# Complexity\n- Time complexity : $$O(N.logN + Q.(26 + logN)) \\approx O(Q.logN)$$\n\n- Space complexity : $$O(26.N + N.logN) \\approx O(N.logN)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Referrence\n1. https://cp-algorithms.com/graph/lca_binary_lifting.html#implementation\n\n# Code\n```\n#define pb push_back\nusing vi = vector<int>;\nconst int mxn = 1E4 + 10, mxk = 18, mxd = 27;\nvector<vi> adj[mxn];\nvi lvl(mxn);\nint dp[mxn][mxk], ps[mxn][mxd];\n\n// Constructs binary lifting dp, ps and lvl\nvoid dfs(int u, int p, int l, int s[]){ // O(N.logN)\n for(int j = 0; j < mxd; j++)ps[u][j] = s[j];\n dp[u][0] = p;\n lvl[u] = l;\n for(int j = 1; j < mxk; j++){\n if(dp[u][j - 1] == -1)continue;\n dp[u][j] = dp[dp[u][j - 1]][j - 1];\n }\n for(auto &e: adj[u]){\n int v = e[0], w = e[1];\n if(v == p)continue;\n s[w] += 1;\n dfs(v, u, l + 1, s);\n s[w] -= 1;\n }\n}\n\n// Finds lca of nodes a and b\nint LCA(int a, int b){ // O(logN)\n if(lvl[a] < lvl[b])swap(a, b);\n int d = lvl[a] - lvl[b];\n for(int i = mxk - 1; i >= 0; i--){\n if(d & (1<<i)){\n a = dp[a][i];\n }\n }\n if(a == b)return a;\n for(int i = mxk - 1; i >= 0; i--){\n if(dp[a][i] != dp[b][i]){\n a = dp[a][i];\n b = dp[b][i];\n }\n }\n return dp[a][0];\n}\n\n// To clear everything up for new testcase\nvoid init(int n){ // O(N.logN)\n for(int i = 0; i < n + 5; i++){\n adj[i].clear();\n for(int j = 0; j < mxk; j++)dp[i][j] = -1;\n for(int j = 0; j < mxd; j++)ps[i][j] = 0;\n }\n}\n\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& E, vector<vector<int>>& Q) {\n init(n);\n for(auto &e: E){\n adj[e[0]].pb({e[1], e[2]});\n adj[e[1]].pb({e[0], e[2]});\n }\n int s[mxd]; vi ans;\n memset(s, 0, sizeof(s));\n dfs(0, -1, 0, s);\n for(auto &e: Q){\n int u = e[0], v = e[1];\n int lca = LCA(u, v);\n int mxf = 0, len = lvl[u] + lvl[v] - 2 * lvl[lca];\n for(int i = 0; i < mxd; i++){\n int feq = ps[u][i] + ps[v][i] - 2 * ps[lca][i];\n mxf = max(mxf, feq);\n }\n int tans = len - mxf;\n ans.pb(tans);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
isomorphic-strings | My 6 lines solution | my-6-lines-solution-by-grandyang-owcf | The idea is that we need to map a char to another one, for example, "egg" and "add", we need to constract the mapping \'e\' -> \'a\' and \'g\' -> \'d\'. Instead | grandyang | NORMAL | 2015-04-29T05:09:35+00:00 | 2018-10-24T10:13:02.317176+00:00 | 162,343 | false | The idea is that we need to map a char to another one, for example, "egg" and "add", we need to constract the mapping \'e\' -> \'a\' and \'g\' -> \'d\'. Instead of directly mapping \'e\' to \'a\', another way is to mark them with same value, for example, \'e\' -> 1, \'a\'-> 1, and \'g\' -> 2, \'d\' -> 2, this works same.\n\nSo we use two arrays here m1 and m2, initialized space is 256 (Since the whole ASCII size is 256, 128 also works here). Traverse the character of both s and t on the same position, if their mapping values in m1 and m2 are different, means they are not mapping correctly, returen false; else we construct the mapping, since m1 and m2 are both initialized as 0, we want to use a new value when i == 0, so i + 1 works here.\n\n\t\n\tclass Solution {\n public:\n bool isIsomorphic(string s, string t) {\n int m1[256] = {0}, m2[256] = {0}, n = s.size();\n for (int i = 0; i < n; ++i) {\n if (m1[s[i]] != m2[t[i]]) return false;\n m1[s[i]] = i + 1;\n m2[t[i]] = i + 1;\n }\n return true;\n }\n }; | 1,016 | 11 | [] | 125 |
isomorphic-strings | Well Explained Simple Java ✅ || Runtime 1 ms✅ || Beats 94.7% ✅ | well-explained-simple-java-runtime-1-ms-cshou | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n Add your time comple | sourabh-jadhav | NORMAL | 2023-02-11T11:58:54.697376+00:00 | 2023-02-11T11:59:26.027875+00:00 | 75,362 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n\n int map1[]=new int[200];\n int map2[]=new int[200];\n\n if(s.length()!=t.length())\n return false;\n\n\n for(int i=0;i<s.length();i++)\n {\n if(map1[s.charAt(i)]!=map2[t.charAt(i)])\n return false;\n\n map1[s.charAt(i)]=i+1;\n map2[t.charAt(i)]=i+1;\n }\n return true;\n }\n}\n```\n\n | 609 | 2 | ['String', 'Java'] | 30 |
isomorphic-strings | Python different solutions (dictionary, etc). | python-different-solutions-dictionary-et-mbll | \nclass Solution(object):\n def isIsomorphic(self, s, t):\n s2t, t2s = {}, {}\n for i in range(len(s)):\n if s[i] in s2t and s2t[s[i | oldcodingfarmer | NORMAL | 2015-07-28T13:36:49+00:00 | 2020-10-22T10:51:20.220385+00:00 | 61,720 | false | ```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n s2t, t2s = {}, {}\n for i in range(len(s)):\n if s[i] in s2t and s2t[s[i]] != t[i]:\n return False\n if t[i] in t2s and t2s[t[i]] != s[i]:\n return False\n s2t[s[i]] = t[i]\n t2s[t[i]] = s[i]\n return True\n \n def isIsomorphic1(self, s, t):\n d1, d2 = {}, {}\n for i, val in enumerate(s):\n d1[val] = d1.get(val, []) + [i]\n for i, val in enumerate(t):\n d2[val] = d2.get(val, []) + [i]\n return sorted(d1.values()) == sorted(d2.values())\n \n def isIsomorphic2(self, s, t):\n d1, d2 = [[] for _ in xrange(256)], [[] for _ in xrange(256)]\n for i, val in enumerate(s):\n d1[ord(val)].append(i)\n for i, val in enumerate(t):\n d2[ord(val)].append(i)\n return sorted(d1) == sorted(d2)\n \n def isIsomorphic3(self, s, t):\n return len(set(zip(s, t))) == len(set(s)) == len(set(t))\n \n def isIsomorphic4(self, s, t): \n return [s.find(i) for i in s] == [t.find(j) for j in t]\n \n def isIsomorphic5(self, s, t):\n return map(s.find, s) == map(t.find, t)\n\n def isIsomorphic6(self, s, t):\n d1, d2 = [0 for _ in xrange(256)], [0 for _ in xrange(256)]\n for i in xrange(len(s)):\n if d1[ord(s[i])] != d2[ord(t[i])]:\n return False\n d1[ord(s[i])] = i+1\n d2[ord(t[i])] = i+1\n return True\n``` | 404 | 7 | ['Python'] | 41 |
isomorphic-strings | Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashMap) | very-easy-100-fully-explained-java-c-pyt-y340 | Two strings s and t are isomorphic if the characters in s can be replaced to get t.\n--------------------------------------------------------------------------- | PratikSen07 | NORMAL | 2022-08-24T07:14:50.407416+00:00 | 2022-08-24T11:26:01.847533+00:00 | 103,918 | false | **Two strings s and t are isomorphic if the characters in s can be replaced to get t.**\n-----------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# **Java Solution:**\n```\n// Runtime: 3 ms, faster than 94.17% of Java online submissions for Isomorphic Strings.\n// Memory Usage: 42.1 MB, less than 95.61% of Java online submissions for Isomorphic Strings.\n// Time Complexity : O(n)\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n // Base case: for different length of two strings...\n if(s.length() != t.length())\n return false;\n // Create two maps for s & t strings...\n int[] map1 = new int[256];\n int[] map2 = new int[256];\n // Traverse all elements through the loop...\n for(int idx = 0; idx < s.length(); idx++){\n // Compare the maps, if not equal, return false...\n if(map1[s.charAt(idx)] != map2[t.charAt(idx)])\n return false;\n // Insert each character if string s and t into seperate map...\n map1[s.charAt(idx)] = idx + 1;\n map2[t.charAt(idx)] = idx + 1;\n }\n return true; // Otherwise return true...\n }\n}\n```\n\n# **C++ Solution:**\n```\n// Time Complexity : O(n)\n// Space Complexity : O(1)\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n // Use hashmaps to save the replacement for every character in the first string...\n unordered_map <char , char> rep;\n unordered_map <char , bool> used;\n // Traverse all elements through the loop...\n for(int idx = 0 ; idx < s.length() ; idx++) {\n // If rep contains s[idx] as a key...\n if(rep.count(s[idx])) {\n // Check if the rep is same as the character in the other string...\n // If not, the strings can\u2019t be isomorphic. So, return false...\n if(rep[s[idx]] != t[idx])\n return false;\n }\n // If no replacement found for first character, check if the second character has been used as the replacement for any other character in the first string...\n else {\n if(used[t[idx]])\n return false;\n // If there exists no character whose replacement is the second character...\n // Assign the second character as the replacement of the first character.\n rep[s[idx]] = t[idx];\n used[t[idx]] = true;\n }\n }\n // Otherwise, the strings are not isomorphic.\n return true;\n }\n};\n```\n\n# **Python Solution:**\n```\n# Time Complexity : O(n)\nclass Solution(object):\n def isIsomorphic(self, s, t):\n map1 = []\n map2 = []\n for idx in s:\n map1.append(s.index(idx))\n for idx in t:\n map2.append(t.index(idx))\n if map1 == map2:\n return True\n return False\n```\n \n# **JavaScript Solution:**\n```\n// Runtime: 83 ms, faster than 88.18% of JavaScript online submissions for Isomorphic Strings.\n// Time Complexity : O(n)\nvar isIsomorphic = function(s, t) {\n // Base case: for different length of two strings...\n if(s.length != t.length)\n return false;\n // Create two maps for s & t strings...\n const map1 = [256];\n const map2 = [256];\n // Traverse all elements through the loop...\n for(let idx = 0; idx < s.length; idx++){\n // Compare the maps, if not equal, return false...\n if(map1[s.charAt(idx)] != map2[t.charAt(idx)])\n return false;\n // Insert each character if string s and t into seperate map...\n map1[s.charAt(idx)] = idx + 1;\n map2[t.charAt(idx)] = idx + 1;\n }\n return true; // Otherwise return true...\n};\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return [*map(s.index, s)] == [*map(t.index, t)]\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 398 | 1 | ['Hash Table', 'String', 'C', 'Python', 'Java', 'Python3', 'JavaScript'] | 30 |
isomorphic-strings | Beats 100% || Easiest Code with comments explained || Beginner Friendly | beats-100-easiest-code-with-comments-exp-oxmr | Intuition\n Describe your first thoughts on how to solve this problem. \nImagine two secret codes, same message but different letters. This code checks if the c | ashimkhan | NORMAL | 2024-04-02T01:27:26.862953+00:00 | 2024-04-02T09:20:25.910046+00:00 | 105,440 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImagine two secret codes, same message but different letters. This code checks if the codes are the same, like matching letters in the same order but ignoring the actual letters themselves.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nImagine two secret messages that use different letters for the same words:\n\nMessage 1: "apple"\nMessage 2: "bbnbm"\n\nThese messages are like isomorphic strings\u2014they have the same structure, just different codes.\n\nHere\'s how the code checks if two strings are isomorphic:\n\nPrepare two counting tables:\n\nOne for string s (like a tally for "apple")\nOne for string t (like a tally for "bbnbm")\nMeasure the length:\n\nIf the messages are different lengths, they can\'t be the same secret message.\nCompare each letter, one by one:\n\nIf a letter appears for the first time in both strings at the same position (like "a" and "b" both appearing first at position 0), make a tally mark for both strings in their respective tables.\nIf a letter appears again, check if its previous position matches in both tally tables. If not, the messages have different codes and aren\'t the same secret message.\nKeep going until the end:\n\nIf you finish comparing all letters and every letter matched up in both tally tables, the messages use the same code and are isomorphic!\nIt\'s like playing a matching game with letters and their positions to see if the two messages have the same secret code!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Java \n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n // Create arrays to store the index of characters in both strings\n int[] indexS = new int[200]; // Stores index of characters in string s\n int[] indexT = new int[200]; // Stores index of characters in string t\n \n // Get the length of both strings\n int len = s.length();\n \n // If the lengths of the two strings are different, they can\'t be isomorphic\n if(len != t.length()) {\n return false;\n }\n \n // Iterate through each character of the strings\n for(int i = 0; i < len; i++) {\n // Check if the index of the current character in string s\n // is different from the index of the corresponding character in string t\n if(indexS[s.charAt(i)] != indexT[t.charAt(i)]) {\n return false; // If different, strings are not isomorphic\n }\n \n // Update the indices of characters in both strings\n indexS[s.charAt(i)] = i + 1; // updating index of current character\n indexT[t.charAt(i)] = i + 1; // updating index of current character\n }\n \n // If the loop completes without returning false, strings are isomorphic\n return true;\n }\n}\n\n\n```\n**C++**\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n vector<int> indexS(200, 0); // Stores index of characters in string s\n vector<int> indexT(200, 0); // Stores index of characters in string t\n \n int len = s.length(); // Get the length of both strings\n \n if(len != t.length()) { // If the lengths of the two strings are different, they can\'t be isomorphic\n return false;\n }\n \n for(int i = 0; i < len; i++) { // Iterate through each character of the strings\n if(indexS[s[i]] != indexT[t[i]]) { // Check if the index of the current character in string s is different from the index of the corresponding character in string t\n return false; // If different, strings are not isomorphic\n }\n \n indexS[s[i]] = i + 1; // updating position of current character\n indexT[t[i]] = i + 1;\n }\n \n return true; // If the loop completes without returning false, strings are isomorphic\n }\n};\n\n```\n\n# Python\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n indexS = [0] * 200 # Stores index of characters in string s\n indexT = [0] * 200 # Stores index of characters in string t\n \n length = len(s) # Get the length of both strings\n \n if length != len(t): # If the lengths of the two strings are different, they can\'t be isomorphic\n return False\n \n for i in range(length): # Iterate through each character of the strings\n if indexS[ord(s[i])] != indexT[ord(t[i])]: # Check if the index of the current character in string s is different from the index of the corresponding character in string t\n return False # If different, strings are not isomorphic\n \n indexS[ord(s[i])] = i + 1 # updating position of current character\n indexT[ord(t[i])] = i + 1\n \n return True # If the loop completes without returning false, strings are isomorphic\n\n\n```\n\n**We can apply same approach using HashMap but for 200 characters this approach suits fine **\n\n\n\n | 366 | 1 | ['C++', 'Java', 'Python3'] | 29 |
isomorphic-strings | 【Video】Keep pairs in HashMap - 2 solutions + Bonus idea. | video-keep-pairs-in-hashmap-2-solutions-w4im3 | Intuition\nKeep pairs in HashMap.\n\n# Solution Video\n\nhttps://youtu.be/5oAh7aopNZ0\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! | niits | NORMAL | 2024-10-10T17:49:19.780937+00:00 | 2024-10-10T17:49:19.780975+00:00 | 33,898 | false | # Intuition\nKeep pairs in `HashMap`.\n\n# Solution Video\n\nhttps://youtu.be/5oAh7aopNZ0\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 9,608\nThank you for your support!\n\n# Solution 1 - Two HashMaps\n\n```\nInput: s = "egg", t = "add"\n```\n\nSimply, each character of both strings should be a pair, that means their indices should be the same.\n\nTo keep character and its index, we use two hashMaps.\n\n```\nchar_index_s = {}\nchar_index_t = {}\n\n```\n\nFirst of all\n\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\ne and a should be index 0\n\nchar_index_s = {e: 0}\nchar_index_t = {a: 0}\n\n```\nNext compare the indices of `e` and `a`. They are the same which is no porblem.\n\nMove next\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\ng and d should be index 1\n\nchar_index_s = {e: 0, g: 1}\nchar_index_t = {a: 0, d: 1}\n\n```\nCompare the indices of `g` and `d`. They are the same which is no porblem.\n\nMove next\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\nchar_index_s = {e: 0, g: 1}\nchar_index_t = {a: 0, d: 1}\n\n```\n`g` and `d` should be index `1`, because we already found the characters at index `1`. To prove that, we have `g` and `d` in `HashMaps`.\n\nCompare `g` and `d`. They are index `1` which is no problem.\n\nNow we reach end of strings.\n\n```\nreturn True\n```\n\nLet\'s see false case. You will understand algorithm deeply. What if the last characters are `a` and `d`.\n```\ns = "ega", t = "add"\n \u2191 \u2191\n\nchar_index_s = {e: 0, g: 1, a: 2}\nchar_index_t = {a: 0, d: 1}\n\n```\nIn that case, `a` is a new character, so add `a` to `HashMap` with index `2`. We already found `d` at index `1`, so we don\'t add this time.\n\nNext, compare indices of `a` and `d`.\n```\na is index 2\nd is index 1\n```\nThey are different indices, **that means we already use `d` with other character.**\n\n```\nreturn False\n```\n\n---\n\nhttps://youtu.be/bU_dXCOWHls\n\n# Complexity\nThis is based on Python. Ohter might be different.\n\n- Time complexity: $$O(n)$$\n`n` is length of input string\n\n- Space complexity: $$O(1)$$\n`s` and `t` consist of any valid ascii character.\n\n```python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n char_index_s = {}\n char_index_t = {}\n\n for i in range(len(s)):\n if s[i] not in char_index_s:\n char_index_s[s[i]] = i\n\n if t[i] not in char_index_t:\n char_index_t[t[i]] = i\n \n if char_index_s[s[i]] != char_index_t[t[i]]:\n return False\n\n return True\n```\n```javascript []\nvar isIsomorphic = function(s, t) {\n const charIndexS = {};\n const charIndexT = {};\n\n for (let i = 0; i < s.length; i++) {\n if (!(s[i] in charIndexS)) {\n charIndexS[s[i]] = i;\n }\n\n if (!(t[i] in charIndexT)) {\n charIndexT[t[i]] = i;\n }\n\n if (charIndexS[s[i]] !== charIndexT[t[i]]) {\n return false;\n }\n }\n\n return true; \n};\n```\n```java []\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n HashMap<Character, Integer> charIndexS = new HashMap<>();\n HashMap<Character, Integer> charIndexT = new HashMap<>();\n\n for (int i = 0; i < s.length(); i++) {\n if (!charIndexS.containsKey(s.charAt(i))) {\n charIndexS.put(s.charAt(i), i);\n }\n\n if (!charIndexT.containsKey(t.charAt(i))) {\n charIndexT.put(t.charAt(i), i);\n }\n\n if (!charIndexS.get(s.charAt(i)).equals(charIndexT.get(t.charAt(i)))) {\n return false;\n }\n }\n\n return true; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, int> charIndexS;\n unordered_map<char, int> charIndexT;\n\n for (int i = 0; i < s.length(); i++) {\n if (charIndexS.find(s[i]) == charIndexS.end()) {\n charIndexS[s[i]] = i;\n }\n\n if (charIndexT.find(t[i]) == charIndexT.end()) {\n charIndexT[t[i]] = i;\n }\n\n if (charIndexS[s[i]] != charIndexT[t[i]]) {\n return false;\n }\n }\n\n return true; \n }\n};\n```\n\n# Step by Step Algorithm\n\n1. **Initialization**:\n ```python\n char_index_s = {}\n char_index_t = {}\n ```\n - **Explanation**: Two empty dictionaries (`char_index_s` and `char_index_t`) are initialized. These dictionaries will store the first index at which each character appears in the strings `s` and `t`, respectively.\n\n2. **Loop Through the Characters**:\n ```python\n for i in range(len(s)):\n ```\n - **Explanation**: A for loop iterates over the range of the length of the string `s`. The variable `i` represents the current index of the characters being processed from both strings.\n\n3. **Check for Characters in `s`**:\n ```python\n if s[i] not in char_index_s:\n char_index_s[s[i]] = i\n ```\n - **Explanation**: For the character at index `i` in string `s`, the code checks if that character is already a key in `char_index_s`. If it is not, it adds the character as a key and sets its value to the current index `i`. This records the first occurrence of the character in `s`.\n\n4. **Check for Characters in `t`**:\n ```python\n if t[i] not in char_index_t:\n char_index_t[t[i]] = i\n ```\n - **Explanation**: Similarly, for the character at index `i` in string `t`, the code checks if it is not already a key in `char_index_t`. If it is not present, the character is added to the dictionary with its index `i`. This records the first occurrence of the character in `t`.\n\n5. **Compare Indices**:\n ```python\n if char_index_s[s[i]] != char_index_t[t[i]]:\n return False\n ```\n - **Explanation**: The code checks whether the index of the current character from `s` in `char_index_s` matches the index of the corresponding character from `t` in `char_index_t`. If they do not match, it means that the characters are not isomorphic (i.e., they do not maintain the same character mapping), so the function returns `False`.\n\n6. **Final Return**:\n ```python\n return True\n ```\n - **Explanation**: If the loop completes without finding any discrepancies, it means that the strings `s` and `t` are isomorphic. The function returns `True`, indicating that there is a one-to-one mapping of characters between the two strings.\n\n---\n\n# Solution 2 - One HashMap\n\nIn solution 2, we use one `HashMap`. We keep characters in `s` as a key and characters in `t` as a value.\n\n```\nInput: s = "egg", t = "add"\n```\n\nFirst of all, we found `e` and `a`. Since we don\'t have any data in `char_map`, just add `e` and `a` to it.\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\nchar_map = {e: a}\n```\nNext, we found `g` and `d`.\n\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\nchar_map = {e: a}\n\nDo we have "g" as a key in char_map? \u2192 No\nDo we have "d" as a value in char_map \u2192 No\nThen, add "g" and "d".\n\nchar_map = {e: a, g: d}\n\n```\n```\ns = "egg", t = "add"\n \u2191 \u2191\n\nchar_map = {e: a, g: d}\n\nDo we have "g" as a key in char_map? \u2192 yes\n\nchar_map[g] != "d" \u2192 no\nthat means we have the same pair before, no problem\n\nchar_map = {e: a, g: d}\n\n```\nFinish iteration.\n\n```\nreturn True\n```\n\n##### Why do we check all values?\n\nSomebody is wondering why we check all values? Let\'s see this example quickly.\n\n```\nInput: s = "egc", t = "add"\n```\nLet\'s iterate throguh one by one without checking values.\n```\ns = "egc", t = "add"\n \u2191 \u2191\n\nDo we have "e" as a key in char_map? \u2192 no\nchar_map = {e: a}\n\n---------------------------\ns = "egc", t = "add"\n \u2191 \u2191\n\nDo we have "g" as a key in char_map? \u2192 no\nchar_map = {e: a, g: d}\n\n---------------------------\ns = "egc", t = "add"\n \u2191 \u2191\n\nDo we have "c" as a key in char_map? \u2192 no\nchar_map = {e: a, g: d, c: d}\n\n```\n```\nreturn True\n```\nThat\'s wrong. `d` created two pairs. \n\n```\n"g" and "d"\n"c" and "d"\n```\nThat happened because we didn\'t check values. Let\'s check them.\n```\ns = "egc", t = "add"\n \u2191 \u2191\n\nDo we have "c" as a key in char_map? \u2192 no\nchar_map = {e: a, g: d}\n\nLet\'s check values.\nDo we have "d" as a value in char_map? \u2192 yes\n```\nThat\'s how we know `d` created two pairs which is not allowed.\n\n```\nreturn False\n```\n\n\n```python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n char_map = {}\n\n for sc, tc in zip(s, t):\n if sc in char_map:\n if char_map[sc] != tc:\n return False\n elif tc in char_map.values():\n return False\n\n char_map[sc] = tc\n\n return True\n```\n```javascript []\nvar isIsomorphic = function(s, t) {\n const charMap = {};\n\n for (let i = 0; i < s.length; i++) {\n const sc = s[i];\n const tc = t[i];\n\n if (charMap[sc]) {\n if (charMap[sc] !== tc) {\n return false;\n }\n } else if (Object.values(charMap).includes(tc)) {\n return false;\n }\n\n charMap[sc] = tc;\n }\n\n return true; \n};\n```\n```java []\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n HashMap<Character, Character> charMap = new HashMap<>();\n\n for (int i = 0; i < s.length(); i++) {\n char sc = s.charAt(i);\n char tc = t.charAt(i);\n\n if (charMap.containsKey(sc)) {\n if (charMap.get(sc) != tc) {\n return false;\n }\n } else if (charMap.containsValue(tc)) {\n return false;\n }\n\n charMap.put(sc, tc);\n }\n\n return true; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, char> charMap;\n\n for (int i = 0; i < s.length(); ++i) {\n char sc = s[i];\n char tc = t[i];\n\n if (charMap.count(sc)) {\n if (charMap[sc] != tc) {\n return false;\n }\n } else {\n for (auto& pair : charMap) {\n if (pair.second == tc) {\n return false;\n }\n }\n charMap[sc] = tc;\n }\n }\n\n return true; \n }\n};\n```\n\n---\n\n# Complexity\nThis is based on Python. Ohter might be different.\n\n- Time complexity: $$O(n)$$\n`n` is length of input string. For values(), it\'s $$O(128)$$ in the worst case.\n\n- Space complexity: $$O(1)$$\n`s` and `t` consist of any valid ascii character.\n\n# Step by Step Algorithm\n\n1. **Initialize an Empty Dictionary**\n ```python\n char_map = {}\n ```\n - This line creates an empty dictionary called `char_map`.\n - This dictionary will store character mappings between the strings `s` and `t`.\n - `char_map` is used to track how characters in `s` are being mapped to corresponding characters in `t`.\n\n2. **Iterate Through Both Strings Simultaneously**\n ```python\n for sc, tc in zip(s, t):\n ```\n - The `zip(s, t)` function pairs corresponding characters from `s` and `t` into tuples.\n - For each tuple `(sc, tc)`, `sc` represents a character from `s` and `tc` represents the corresponding character from `t`.\n - The `for` loop iterates through each character pair one-by-one.\n\n3. **Check if `sc` (Character from `s`) is Already Mapped**\n ```python\n if sc in char_map:\n ```\n - This line checks if `sc` (the character from `s`) is already a key in the `char_map`.\n - If `sc` is found in `char_map`, it means there is an existing mapping between `sc` and some character from `t`.\n\n4. **Verify the Existing Mapping**\n ```python\n if char_map[sc] != tc:\n return False\n ```\n - If `sc` is already mapped, this line checks if the existing mapping (`char_map[sc]`) matches the current character from `t` (`tc`).\n - If it doesn\u2019t match, the function returns `False` because this means the same character from `s` is trying to map to a different character in `t`, violating the isomorphism property.\n\n5. **Check if the Character `tc` (from `t`) is Already Mapped by Another Character**\n ```python\n elif tc in char_map.values():\n return False\n ```\n - This line checks if the current character from `t` (`tc`) is already a value in `char_map`.\n - If `tc` is already mapped to some other character from `s`, it means a character from `t` is mapped by more than one character from `s`.\n - This also violates the isomorphism property, so the function returns `False`.\n\n6. **Create a New Mapping Between `sc` and `tc`**\n ```python\n char_map[sc] = tc\n ```\n - If neither of the above conditions is met, it means `sc` is not in `char_map` and `tc` is not already mapped by another character.\n - This line creates a new mapping from `sc` to `tc` in the dictionary.\n\n7. **If No Violations are Found, the Strings are Isomorphic**\n ```python\n return True\n ```\n - If the function successfully iterates through all the character pairs without finding any violations, it returns `True`.\n - This indicates that `s` and `t` are isomorphic.\n\n---\n\n\n# Bonus\n\nIf number of unique characters are the same and number of unqiue pairs are the same, we can return true.\n\n```python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s)) == len(set(t)) == len(set(zip(s,t)))\n```\n\nFor eaxample,\n\n```\ns = "egg", t = "add"\n\nset(s) \u2192 "eg"\nset(t) \u2192 "ad"\nset(zip(s,t)) \u2192 (e,a), (g,d)\n\n```\n\n##### Why do we need set(zip(s,t))?\n\nThere are cases where number of unique characters are the same but unique pairs are invalid.\n\nLet\'s see this example.\n```\ns = "bba", t = "aba"\n\nset(s) \u2192 "ba"\nset(t) \u2192 "ab"\nset(zip(s,t)) \u2192 (b,a), (b,b), (a,a)\n\n```\nWe use `b` for `a`(= (b,a)) and `b` (= (b,b)) when we create unique pairs. That is invalid. \n\nIf we check only\n\n```\nlen(set(s)) == len(set(t))\n```\nWe will return `true` but expected return value should be `false`.\n\n---\n\nThank you for reading my post. Please upvote it and don\'t forget to subscribe to my channel!\n\n### \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n### \u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### \u2B50\uFE0F Related question \n#162 - Find peak element\n\nhttps://youtu.be/Xmo54xPn7Ao | 270 | 1 | ['Hash Table', 'String', 'C++', 'Java', 'Python3', 'JavaScript'] | 9 |
isomorphic-strings | Short Java solution without maps | short-java-solution-without-maps-by-shpo-9lea | Hi guys!\n\nThe main idea is to store the last seen positions of current (i-th) characters in both strings. If previously stored positions are different then we | shpolsky | NORMAL | 2015-04-29T12:00:22+00:00 | 2018-10-22T05:16:07.169788+00:00 | 67,853 | false | Hi guys!\n\nThe main idea is to store the last seen positions of current (i-th) characters in both strings. If previously stored positions are different then we know that the fact they're occuring in the current i-th position simultaneously is a mistake. We could use a map for storing but as we deal with chars which are basically ints and can be used as indices we can do the whole thing with an array.\n\nCheck the code below. Happy coding! \n\n----------\n\n public class Solution {\n public boolean isIsomorphic(String s1, String s2) {\n int[] m = new int[512];\n for (int i = 0; i < s1.length(); i++) {\n if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;\n m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;\n }\n return true;\n }\n } | 223 | 8 | ['Java'] | 34 |
isomorphic-strings | 1 line in Python | 1-line-in-python-by-numerical-3y9w | def isIsomorphic(self, s, t):\n return len(set(zip(s, t))) == len(set(s)) and len(set(zip(t, s))) == len(set(t)) | numerical | NORMAL | 2015-06-21T00:58:02+00:00 | 2018-10-19T13:08:44.370225+00:00 | 21,898 | false | def isIsomorphic(self, s, t):\n return len(set(zip(s, t))) == len(set(s)) and len(set(zip(t, s))) == len(set(t)) | 187 | 0 | ['Python'] | 28 |
isomorphic-strings | 2 liner with 99% efficiency and explanation. | 2-liner-with-99-efficiency-and-explanati-zn2l | Runtime: 32 ms, faster than 99.09% of Python3 online submissions for Isomorphic Strings.\nMemory Usage: 14.2 MB, less than 96.77% of Python3 online submissions | AmrinderKaur1 | NORMAL | 2021-07-14T13:04:47.463864+00:00 | 2022-02-26T07:19:44.215752+00:00 | 9,783 | false | Runtime: 32 ms, faster than 99.09% of Python3 online submissions for Isomorphic Strings.\nMemory Usage: 14.2 MB, less than 96.77% of Python3 online submissions for Isomorphic Strings\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n zipped_set = set(zip(s, t))\n return len(zipped_set) == len(set(s)) == len(set(t))\n \n```\nExplanation:\nwhy using zip ?\n=> zip function would pair the first item of first iterator (i.e `s` here) to the first item of second iterator (i.e `t` here). `set()` would remove duplicate items from the zipped tuple. It is like the first item of first iterator mapped to the first item of second iterator as it would in case of a hashtable or dictionary.\nUnderstand using exmaples:\n```\n# when strings ae isomorphic:\ns = "egg"\nt = "add"\n\nzipped_set = {(\'e\', \'a\'), (\'g\', \'d\')}\n# now comparing their lengths when duplicacies are removed\nreturn len(zipped_set) == len(set(s)) == len(set(d))\n# return 2 == 2 == 2 -> True\n```\n```\n# when strings are not isomorphic:\ns = "egk"\nt = "add"\n\nzipped_set = {(\'e\', \'a\'), (\'g\', \'d\'), (\'k\', \'d\')}\n# now comparing their lengths when duplicacies are removed\nreturn len(zipped_set) == len(set(s)) == len(set(d))\n# return 3 == 3 == 2 -> False\n```\n | 183 | 0 | ['Ordered Set', 'Python', 'Python3'] | 15 |
isomorphic-strings | Super Easy Solution || C++|| Hashtable | super-easy-solution-c-hashtable-by-himan-pblk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\n# Complexity\n- Time complexity:\nO(|str1|+|str2|). Add your time compl | himanshu__mehra__ | NORMAL | 2023-01-06T09:39:09.414658+00:00 | 2023-01-06T09:39:09.414717+00:00 | 38,721 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n# Complexity\n- Time complexity:\nO(|str1|+|str2|).<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(Number of different characters).<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, char> mp, mp2;\n for (int i=0; i<s.length(); ++i) {\n if (mp[s[i]] && mp[s[i]]!=t[i]) return false;\n if (mp2[t[i]] && mp2[t[i]]!=s[i]) return false;\n mp[s[i]]=t[i];\n mp2[t[i]]=s[i];\n }\n return true;\n }\n};\n```\nPlease upvote to motivate me to write more solutions | 182 | 0 | ['C++'] | 22 |
isomorphic-strings | Java solution using HashMap | java-solution-using-hashmap-by-screddy-t6b0 | public class Solution {\n public boolean isIsomorphic(String s, String t) {\n if(s == null || s.length() <= 1) return true;\n HashM | screddy | NORMAL | 2015-05-18T01:41:30+00:00 | 2018-10-18T05:38:11.720402+00:00 | 59,920 | false | public class Solution {\n public boolean isIsomorphic(String s, String t) {\n if(s == null || s.length() <= 1) return true;\n HashMap<Character, Character> map = new HashMap<Character, Character>();\n for(int i = 0 ; i< s.length(); i++){\n char a = s.charAt(i);\n char b = t.charAt(i);\n if(map.containsKey(a)){\n if(map.get(a).equals(b))\n continue;\n else\n return false;\n }else{\n if(!map.containsValue(b))\n map.put(a,b);\n else return false;\n \n }\n }\n return true;\n \n }\n } | 173 | 17 | ['Java'] | 30 |
isomorphic-strings | One Line of Code and Using Hashtable Python | one-line-of-code-and-using-hashtable-pyt-z8kq | One Line of Code Python Solution\n\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s))==len(set(t))==len(set(zip(s | GANJINAVEEN | NORMAL | 2023-04-16T07:08:37.020680+00:00 | 2023-04-16T07:08:37.020721+00:00 | 10,480 | false | # One Line of Code Python Solution\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s))==len(set(t))==len(set(zip(s,t)))\n```\n# please upvote me it would encourage me alot\n\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n dic1,dic2={},{}\n for s1,t1 in zip(s,t):\n if (s1 in dic1 and dic1[s1]!=t1) or ( t1 in dic2 and dic2[t1]!=s1):\n return False\n dic1[s1]=t1\n dic2[t1]=s1\n return True\n \n```\n# please upvote me it would encourage me alot\n | 103 | 0 | ['Python3'] | 6 |
isomorphic-strings | 1 Line Python||4 Line Java||8 Line C++||Beats98% | 1-line-python4-line-java8-line-cbeats98-wygj7 | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n___\n__\nQ | Anos | NORMAL | 2022-10-14T07:19:34.307151+00:00 | 2022-10-20T15:29:30.391955+00:00 | 17,182 | false | ***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q205. Isomorphic Strings***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s))==len(set(zip(s,t)))==len(set(t))\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n Map m = new HashMap();\n for (Integer i=0; i<s.length(); ++i)\n\t\t\tif (m.put(s.charAt(i), i) != m.put(t.charAt(i)+"", i)) return false;\n return true;\n }\n}\n```\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, char> m1, m2;\n for (int i = 0; i < s.size(); i++) {\n if (!m1.count(s[i]) && !m2.count(t[i]))\n m1[s[i]] = t[i];m2[t[i]] = s[i];\n else \n\t\t\t\t\tif (m1[s[i]] != t[i] || m2[t[i]] != s[i]) return false;\n }\n return true;\n }\n};\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 98 | 2 | ['C', 'Python', 'Java'] | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.