• + 0 comments

    I tried this using C++ and came up with a DSU solution but it seems to not pass 6 test cases out of 13, can anyone help me with it?

    include

    using namespace std;

    string ltrim(const string &); string rtrim(const string &); vector split(const string &);

    /* * Complete the 'roadsAndLibraries' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. INTEGER c_lib * 3. INTEGER c_road * 4. 2D_INTEGER_ARRAY cities */

    class Disjoint{ public: vectorsize,parent; Disjoint(int n){ size.resize(n+1,1); parent.resize(n+1,0); for(int i=0;i<=n;i++) parent[i]=i; }

    int findUParent(int node){ if(node==parent[node]) return node; return parent[node]=findUParent(parent[node]); }

    void unionBySize(int u, int v){ int ulp_u=findUParent(u); int ulp_v=findUParent(v); if(ulp_u==ulp_v) return; else if(size[ulp_u]>size[ulp_v]){ parent[ulp_v]=ulp_u; size[ulp_u]+=size[ulp_v]; } else{ parent[ulp_u]=ulp_v; size[ulp_v]+=size[ulp_u]; } } };

    long roadsAndLibraries(int n, int c_lib, int c_road, vector> cities) { if(c_road>=c_lib) return static_cast(n)*c_lib; Disjoint d(n); // int n=cities.size(); // int m=cities[0].size(); int tot=0,city=0; unordered_setst; for(auto x:cities){ if(d.findUParent(x[0])!=d.findUParent(x[1])){ d.unionBySize(x[0],x[1]); tot+=c_road; } } for(int node=1;node<=n;node++) st.insert(d.findUParent(node)); city=st.size(); tot+=city*c_lib; return (long)tot; }

    int main()