Sort by

recency

|

28 Discussions

|

  • + 0 comments

    Here is my solution in java, javascript, python, C, C++, Csharp HackerRank Tree Pruning Problem Solution

  • + 0 comments

    Here is Tree Pruning problem solution in Python Java C++ and C programming - https://programs.programmingoneonone.com/2021/07/hackerrank-tree-pruning-problem-solution.html

  • + 0 comments

    There you go, PyPy 3 solution :-)

    # Enter your code here. Read input from STDIN. Print output to STDOUT
    import itertools
    
    class Graph:
        def __init__(self, weights):
            self.n = len(weights)
            self.weights = [0] + weights
            self.edges = [[] for _ in range(n + 1)]
            
    def diffs(seq):
        d = []
        for i in range(len(seq) - 1):
            d.append(seq[i + 1] - seq[i])
        return d
    
    def distributions(elems, picks):
        assignments = itertools.combinations_with_replacement(elems + [None], picks)
        def dist_for_assignment(assgn):
            picks_by_elem = dict(((elem, len(list(picks))) for (elem, picks) in itertools.groupby(assgn)))
            return dict(((elem, picks_by_elem.get(elem, 0)) for elem in elems))
        return (dist_for_assignment(a) for a in assignments)
          
    def max_sum(g, k):
        visits = []
        seen = [False for _ in range(g.n + 1)]
        stack = [1]
        while stack:
            v = stack.pop()
            visits.append(v)
            seen[v] = True
            i = 0
            while i < len(g.edges[v]):
                nv = g.edges[v][i]
                if seen[nv]:
                    g.edges[v].pop(i)
                else:
                    stack.append(nv)
                    i += 1       
        sums = [[] for _ in range(g.n + 1)]
        for v in reversed(visits):
            children = g.edges[v]
            if not children:
                # no edges to remove
                sums[v] = [g.weights[v]]
            else:
                child_sums = [sums[c] for c in children]
                total_cuts = sum((len(sums[c]) - 1 for c in children))
                combined_sums = sums[children[0]]
                for child_idx in range(1, len(children)):
                    child_sums = sums[children[child_idx]]
                    new_combined_sums = [-(1 << 64) for _ in range(total_cuts + 1)]
                    # best distribution of total_cuts among [:child_idx] children
                    for cuts in range(total_cuts + 1):
                        for cuts1 in range(cuts + 1):
                            if cuts1 >= len(combined_sums) or cuts - cuts1 >=len(child_sums):
                                continue
                            new_combined_sums[cuts] = max(new_combined_sums[cuts], combined_sums[cuts1] + child_sums[cuts - cuts1])
                    combined_sums = new_combined_sums
                sums[v] = [s + g.weights[v] for s in combined_sums]        
            if v > 1:
                # we could cut off this node if not root
                if len(sums[v]) == 1:
                    if sums[v][0] < 0:
                        sums[v].append(0)
                elif sums[v][1] < 0:
                    sums[v][1] = 0               
            # more cuts for less never makes sense
            max_sum_idx = 1
            for i in range(1, len(sums[v])):
                sums[v][i] = max(sums[v][i], 0)
                if sums[v][i] > sums[v][max_sum_idx]:
                    max_sum_idx = i
            sums[v] = sums[v][:min(max_sum_idx,k) + 1]    
        return sums[1][min(k, len(sums[1]) - 1)]
    
    n, k = map(int, input().split())
    w = list(map(int, input().split()))
    g = Graph(w)
    for _ in range(n - 1):
        a, b = map(int, input().split())
        g.edges[a].append(b)
        g.edges[b].append(a)
    print(max_sum(g, k))
    
  • + 0 comments

    C++ Solution

    #include <bits/stdc++.h>
    
    using namespace std;
    
    const int MAXN = 100000 + 2;
    const int MAXK = 200 + 2;
    const long long INF = -(long long)(1e15);
    
    vector<int> g[MAXN];
    int n, k, val[MAXN];
    long long dpn[MAXK];
    
    inline void update(long long& x, long long y) {
        x = max(x, y);
    }
    
    void dfs(int x, int f) {
        long long dpc[MAXK], dptmp[MAXK];
        fill (dpc, dpc + k + 1, INF);
        dpc[0] = val[x];
    
        for (const int& next : g[x]) {
            if (next != f) {
                dfs (next, x);
                fill (dptmp, dptmp + k + 1, INF);
                for (int ck = 0; ck <= k; ++ck) {
                    if (dpc[ck] == INF) {
                        break ;
                    }
                    for (int nk = 0; nk + ck <= k; ++nk) {
                        if (dpn[nk] == INF) {
                            break ;
                        }
                        update (dptmp[ck + nk], dpc[ck] + dpn[nk]);
                    }
                    if (ck + 1 <= k) {
                        update (dptmp[ck + 1], dpc[ck]);
                    }
                }
                copy (dptmp, dptmp + k + 1, dpc);
            }
        }
        copy (dpc, dpc + k + 1, dpn);
    }
    
    void solve() {
        dfs (0, -1);
        cout << max(0LL, *max_element(dpn, dpn + k + 1)) << endl;
    }
    
    int main() {
        while (scanf ("%d%d", &n, &k) != EOF) {
            for (int i = 0; i < n; ++i) {
                g[i].clear();
                scanf ("%d", &val[i]);
            }
            for (int i = 0; i < n - 1; ++i) {
                int u, v;
                scanf ("%d%d", &u, &v);
                g[--u].push_back(--v);
                g[v].push_back(u);
            }
            solve();
        }
        return 0;
    }
    
  • + 0 comments

    Can some one help me out by explaining why my code fails?

    #include<bits/stdc++.h>
    #define lld      long
    #define mp       make_pair
    #define pb       push_back
    #define ff       first
    #define ss       second
    #define pll      pair<lld,lld>
    #define pii      pair<int,int>
    #define vll      vector<lld>
    #define vii      vector<int>
    #define umap     unordered_map
    #define lb       lower_bound
    #define ub       upper_bound
    #define mod      1000000007
    #define all(x)   x.begin(),x.end()
    #define sort1(x) sort(x,greater<int>())
    #define rep(i,a,b) for(i = a; i < b; i++)
    #define fio      ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
    using namespace std;
    
    namespace forever {
        template<class type1,class type2>
            inline istream &operator>>(istream &in,pair<type1,type2> &p)
            {
                in>>p.ff>>p.ss;
                return in;
            }
        template<class type1,class type2>
            inline ostream &operator<<(ostream &o,pair<type1,type2> &p)
            {
                 o<<"("<<p.ff<<","<<p.ss<<")";
                return o;
            } 
        template<class type>
            inline ostream &operator<<(ostream &o,vector<type> &v)
            {
                for(int i=0;i<v.size();i++)
                    o<<v[i]<<" ";
                return o;    
            }
        template<class t>
            inline istream &operator>>(istream &in,vector<t> &p)
            {
                for(auto & x : p)
                    in >> x;
                return in;
            }
        struct custom_hash {
            static uint64_t splitmix64(uint64_t x) {
                x += 0x9e3779b97f4a7c15;
                x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
                x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
                return x ^ (x >> 31);
            }
            size_t operator()(uint64_t x) const {
                static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
                return splitmix64(x + FIXED_RANDOM);
            }
        };
    }
    using namespace forever;
    struct comp{
        bool operator ()(pii const& a,pii const& b){
                return a.ss > b.ss;
        }
    };
    
    vii adj[100001];
    vii a(100001);
    priority_queue<pii,vector<pii>,comp> sr;
    umap<int,bool,custom_hash> vis;
    umap<int,int,custom_hash> level;
    int dfs(int u){
        int x=0,i;
        vis[u] = true;
        if(!adj[u].size()){   
            sr.push({u,a[u-1]});
            return a[u-1];
        }
        for(i=0;i<adj[u].size();i++){
            if(!vis[adj[u][i]] && level[adj[u][i]] >= level[u])
                x += dfs(adj[u][i]);
        }
        x += a[u-1];
        sr.push({u,x});
        return x;
    }
    
    
    void dfs1(int u){
        vis[u] = true;
        for(int i=0;i<adj[u].size();i++){
            if(!vis[adj[u][i]] && level[adj[u][i]]>=level[u])
                dfs1(adj[u][i]);
        }
    }
    void bfs(){
        int i,u = 1;
        queue<int> q;
        q.push(u);
        level[u] = 1;
        while(!q.empty()){
            u = q.front();
            vis[u] = true;
            q.pop();
            for(i=0;i<adj[u].size();i++){
                if(!vis[adj[u][i]]){
                    q.push(adj[u][i]);
                    level[adj[u][i]] = level[u] + 1;
                }
            }
        }
    }
    
    void test_cases(){
        int n,k,i,u,v;
        cin >> n >> k;
        a.resize(n);
        cin >> a;
        lld tsum = 0;
        for(int x: a){
            tsum += x;
        }
        //cout << tsum << "\n";
        for(i=0;i<n-1;i++){
            cin >> u >> v;
            adj[u].pb(v);
            adj[v].pb(u);
        }
        bfs();
        vis.clear();
        int te = dfs(1);
        vis.clear();
        /*while(!sr.empty()){
            cout << sr.top().ff << " " << sr.top().ss << "\n";
            sr.pop();
        }*/
        
        while(k-- && !sr.empty()){
            pii ram = sr.top();
            //cout << ram.ff << "\n";
            sr.pop();
            if(vis[ram.ff] || ram.ff==1){
                k++;
                continue;
            }
            //cout << "\n";
            if(ram.ss>-1)
                break;
            dfs1(ram.ff);    
            tsum -= ram.ss;
            //cout << tsum << "\n";
        }
        cout << tsum << "\n";
    }
    
    int main()
    {
        fio;     
        //#ifndef ONLINE_JUDGE 
        //freopen("ip.txt","r",stdin);
           //freopen("sout.txt","w",stdout);
        //#endif
        
        int  t=1;
        //cin >> t;
        while(t--){
            test_cases();
        }
        
        return 0;
    }