We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Roads and Libraries
Roads and Libraries
Sort by
recency
|
878 Discussions
|
Please Login in order to post a comment
I try very hard, buts for now I dont know whats is wrong with my code, can somebody help please?
class Result {
}
with custom input 1 5 3 6 1 1 2 1 3 1 4 it returns an expected answer of 15 when infact its 9. ie c_lib = 6 c_road = 1 1 library + 3 roads = 9 not 15 1 libraries + 3 roads = 15
Compiler Message: Wrong Answer
Input (stdin) 1 5 3 6 1 1 2 1 3 1 4 Your Output (stdout) 9
Any ideas why my answer is wrong? 4 cities in one aglomeration, cost of library 6 and cost of road 1. It's simply one library (6) and 3 roads (3) what all gives 9. Do I misunderstand something, or hackerrank has a bug?
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()
To enhance your community’s infrastructure, consider the "Roads and Libraries" initiative. This program focuses on improving road networks and expanding library resources, ensuring better connectivity and access to knowledge. Explore our promotional items, which include detailed project plans and funding options, to support these essential upgrades. Investing in roads and libraries not only improves daily commutes but also fosters educational growth and community development. Get involved today!