Whats wrong with this CodeChef: Practical coding for everyone
Please star my projects and contribute if you are interested.
Can someone please point out the mistake in this code?
Code-(CodeChef: Practical coding for everyone)
Thanks
such a nice problem, thank you codechef.
Used union find but kept getting TLE. Code:gDZvZc - Online C++0x Compiler & Debugging Tool - Ideone.com
Would be really helpful if someone could point out the mistake in this.
very good question …
You have loop for(int j=i; j<n; j++)
after each call to dfs. In the case of no edges in the graph you will have O(N^2)
solution. Obviously it should get TLE
@anton_lunyov >> So, if I consider the case of graph consisting of no edges separately, will it run within TL?
Replace c[p[i]]++
by c[find(i)]++
p[i]
is not always the actual root of the disjoint set containing i
.
Namely, after link operation.
No. The graph could have many components, say 90000, and you still will get TLE. Also why you are creating the array visited
at each dfs
run? This is the worst thing to do. It should be created only once and filled by false
before global dfs
loop
and that is why my code was 270M
Use ret = ((long long)ret * c) % 1000000007;
I used weighted quick union for this, which can be improved further using path compression.
My solution : http://www.codechef.com/viewplaintext/1869801
@ anton : Thanks a lot…
They both have the same mistake. You do not handle possible overflow in this statement
total = ((total % N)*(count % N) % N;
As you can see, because N is 1000000007, the result of the product might exceed the range of 32-bit integers. You must cast total as long long in C to solve the issue. Cast total to long in JAVA to get AC.
Checkout the fixes here.
I could point out two bugs
- You have to find uniques in the id array. You are simply parsing over it and inserting ‘i’ instead of find(i) in the HashSet.
- Multiplying everything and storing in a long will potentially overflow. It is fixed by storing the result modulo 1000000007 along the way.
Try this test case
1 4 3 1 2 1 3 4 3
You print
2 4
The answer should be
1 4
Can you see how?