Advertisement
maycod23

Untitled

Feb 16th, 2023
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. class Solution {
  2. public:
  3. long long dfs(vector<vector<int>>& adj,int cur,int par,
  4. vector<int>& price, vector<map<int,long long>>& dp)
  5. {
  6. if(dp[cur].count(par)) return dp[cur][par];
  7. long long ans=0;
  8. for(auto i:adj[cur]){
  9. if(i==par) continue;
  10. ans=max(ans,dfs(adj,i,cur,price,dp));
  11. }
  12. dp[cur][par]=(ans+price[cur]);
  13. return dp[cur][par];
  14. }
  15. long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {
  16. vector<vector<int>> adj(n);
  17. for(auto &i: edges){
  18. adj[i[0]].push_back(i[1]);
  19. adj[i[1]].push_back(i[0]);
  20. }
  21. vector<map<int,long long>> dp(n);
  22. long long ans=0;
  23. for(int i=0;i<n;i++){
  24. if(adj[i].size()==1){
  25. //make i as root, get the ans and maximise that
  26. long long temp=dfs(adj,i,-1,price,dp)-price[i];
  27. ans=max(ans,temp);
  28. }
  29. }
  30. return ans;
  31. }
  32. };
  33.  
  34.  
  35.  
  36. /*
  37. given n nodes [0,n-1], prices of n nodes, undirected and unrooted and non cyclic tree, tak any node as root and find max price sum - min price sum and maximise this.
  38.  
  39. brute force->
  40. take each node as root and find max - price of root and maximise this , but problem is this will take O(n^2) time,
  41. opti-1: when finding answers for any particluar root we will be exploring all of its childrens als but we can't use that answers stored why?
  42. -> beacuse that will be giving the answers of that particluar subtree while subtree is also changing.
  43.  
  44. so it depends on who is calling which node.
  45.  
  46. op-1: brute force -> O(n^2)
  47. op-2: storing answers for each root -> not covering the whole subtree
  48. op-3: store who had called whom
  49. op-4: make root only those who has one childrens only, that will maximise that
  50.  
  51.  
  52.  
  53.  
  54. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement