My code is not working on codeblocks but is working on online compiler.
It shows filename.exe has stopped working without taking any input
link to code :
My code is not working on codeblocks but is working on online compiler.
It shows filename.exe has stopped working without taking any input
link to code :
Hi Team, I recently solved SPOJ HERDING, using bfs approach by calculating the number of connecting components using 2D matrix method, but I am getting the wrong answer for some test cases.I figured out some of them which are:
4 4
SWWW
SEEW
SSWS
NNWN
Here is link to my code.If anyone can help......that's would be great.
Author:Dmytro Berezin
Tester:Pawel Kacprzak and Misha Chorniy
Editorialist:Bhuvnesh Jain
EASY-MEDIUM
Segment trees, Deque, Rotation trick
You are given an array $A$ consisting of 0 and 1. You need to perform 2 type of queries of the array.
Remove the rotation part in problem by duplicating the array. Pre-compute the answer for each window of size less than or equal to $k$. Use segment trees to answer the maximum in a range.
Let us first remove the query regarding rotation from the problem. This is a known trick where we remove the rotation using duplication of the array. To consider this aspect, see this example below :
Let array $A$ be $\{1, 0, 0, 1, 1\}$. Duplicate this array i.e. $\{1, 0, 0, 1, 1, 1, 0, 0, 1, 1\}$ and call it as $B$. Now, you can see that we can obtain all the arrays possible after rotation. They are just contiguous sub-arrays of length $n$ in the above array $B$. For example, after 2 rotations, we can consider the subarray from position 3 to 7 as the required array. (0-based indexing)
Now, for the rotation query, we just need to handle the starting position in the above array $B$. So, these queries can be handled in $O(1)$
Once, we have removed the rotations part from the problem, we can pre-compute the number of 1's in window of size $k$ for all sub-arrays in $B$. Also, since we want to maximise the number of 1's in the frame, we can always greedily chose frame of size $k$ only. Doing this in a naive way will take complexity $O(n^2)$, as we will loop over sub-arrays and each sub-array will take $O(n)$ in worst case. We can using sliding window concept here to calculate the number of ones in all frames of size $k$. The logic behind this is as follows :
First we compute the answer for all positions which are less the $k$. After that, suppose we want to find the answer for a position starting at, say $x$ and ending at $(x+k-1)$. We see that only one element moves out of the window and only one element enters the windows as we slide it. Thus, these operations can be done in $O(n)$. Below is a pseudo code for it.
sum[0] = 0
for i in 1 to k:
sum[i] = sum[i-1] + b[i]
for i in k+1 to 2*n:
sum[i] = sum[i-1] + b[i] - b[i-k]
For the sample array $B$ given above and choosing $k = 3$, the sum array will look like $\{1, 1, 1, 1, 2, 3, 2, 1, 1, 2\}$.
Now, once we have calculated all the above sums, the question just reduces to finding the windows with maximum sum. Now, if the window is of size greater than or equal to the array size, then the answer is always the number of ones in the array else the answer is the maximum sum we can obtain by starting the window from $1$ to $(n-k+1)$. These range maximum queries can be easily with segment trees, sparse tables or in this specific cases using deques.
For handling the above minimum queries using segment trees or sparse table, one can refer to this editorial at topcoder . For understanding a better algorithm, which uses deque and works in $O(n)$, one can refer to this problem from Spoj.
$O(n \log{n})$, if using segment trees / sparse tables
$O(n)$ if using deques
Problem code: https://www.codechef.com/problems/SAMESNAK/
Solution: https://www.codechef.com/viewsolution/14248132
My solution is pretty much editorial solution, could someone please tell me what mistake I have made?
i want a good link to understand time and space complexity of a program. a video or article link ... if video ,it will be better to understand...
Link to solution :
I am solving range minimum query for segment tree but update operation is giving wrong output.
Testcase :
6 5
1 5 2 4 3 0
q 1 5
u 5 -1
q 1 5
q 1 4
q 1 3
This assumes you already have a basic knowledge of segment trees.For this discussion, I want to show everyone that persistence can actually be made simple just by changing our way of thinking.
Usually, persistence is treated as a "really hard" kind of data structure. After all, it's like a dream data structure with robust version control. It's the crowd favorite for long challenges because of its fame to as the "hardest to implement", especially when appended with truly hard concepts in other topics. In reality, persistence can actually be made simple, as it is literally only one step away from the non-persistent version.
Why does the idea of a persistent data structure seem so hard for most programmers? I think this is because most of us started with imperative programming languages like C++, Java, and Python, where changing values of variables is the norm. We are familiar with having the power to mutate a value anytime we want. In contrast, most of us cringe whenever we deal with immutables. Hail C++ mutable std::string
, screw Java's immutable String
. Nothing beats plain simple assignment operator (s[i] = c
) compared to the read-only (s.charAt(i)
). Most, if not all of us, grew with the imperatively mutable mindset. We live and breathe with mutability. It is our intuitive art.
But when you think about it, persistence is all about staying immutable. Being persistent means we discard our powers of mutability. Just like how Java's String
class is immutable, we avoid changing individual values directly. Though at first this seems dumb and inefficient, when you think about it it's the straightforward way to do version control. Since original content stays the same, having a new version of the content won't damage the version of the original. For immutables, the way to "change" is to "create". The fact is that persistence == immutability
, and so we can summarize the act such act of staying persistent with one golden rule.
Create new nodes instead of changing them.
That's it? Yes, that's it! That's the only additional step we need to transform from mutable to persistent. The way is by REMOVING our capability to be mutable, at least on the side of our data structure. We force ourselves to CREATE new nodes when we update, so that original content can stay the same.
Persistence is actually straightforward. There's no need to fancy things around. Just replace all assignment operators with new node
expression or similar. It is no exaggeration to say that it is a mere few lines of code away from the mutable version. The "god data structure" everyone thinks is so complicated is in truth something with removed powers than the original. But with this irony of a removed power, we get a new powerful way to do version control.
Let's demonstrate an example of adding persistence to a segment tree. Suppose we want to solve the range sum query problem, but with a persistent data structure. We could implement it the usual segment tree way as follows:
#define M ((L+R)/2)
int st[4*n];
void build(int arr[], int p=1, int L=0, int R=n-1) {
if (L == R) st[p] = arr[L]; // construct as leaf
else { // construct as parent
build(arr, 2*p, L, M);
build(arr, 2*p+1, M+1, R);
st[p] = st[2*p] + st[2*p+1];
}
}
Now how do we make this persistent? What we do is that we replace every assignment operator st[p] = ??
with a new
operator. See my example below for the details.
#define M ((L+R)/2)
int build(int arr[], int L=0, int R=n-1) {
if (L == R) return newleaf(arr[L]); // construct as leaf
else return newparent(build(arr, L, M), build(arr, M+1, R)); // construct as parent
}
Isn't it really simple? We abstract the idea of "change" via "creation", as per the golden rule of persistence. In fact, in some cases, we can achieve shorter code than the mutable version if we do it this way! Of course, this depends on the problem, but it is not wrong to say that it can be achievable.
If you think about it, the difference between the non-persistent and the persistent version is that the former mutates an array called st[]
while the latter returns a new node at every build. You can implement this a couple of ways; usually, the way I implement it is by allocating a pooled array:
int l[SIZE], r[SIZE], st[SIZE], NODES = 0;
int newleaf(int value) {
int p = ++NODES;
l[p] = r[p] = 0; // null
st[p] = value;
return p;
}
int newparent(int lef, int rig) {
int p = ++NODES;
l[p] = lef;
r[p] = rig;
st[p] = st[lef] + st[rig]; // immediately update value from children
return p;
}
We can either construct as a leaf or as a parent, where constructing the latter already pulls values from the children. In the same way as the mutable version, we have an array that stores the segment tree values depending on our queries. Each node also has pointer to the left and the right children stored at l[]
and r[]
respectively. For the size, I usually allocate around $SIZE \approx 8N \lceil log N \rceil$. Of course, an alternative is to use classes instead of a pooled array. It all depends on your groove :)
void update(int i, int x, int p=1, int L=0, int R=n-1) {
if (L == R) {st[p] = x; return;}
if (i <= M) update(i, x, 2*p, L, M);
else update(i, x, 2*p+1, M+1, R);
st[p] = st[2*p] + st[2*p+1];
}
// return an int, a pointer to the new root of the tree
int update(int i, int x, int p, int L=0, int R=n-1) {
if (L == R) return newleaf(st[p] + x);
if (i <= M) return newparent(update(i, x, l[p], L, M), r[p]);
else return newparent(l[p], update(i, x, r[p], M + 1, R));
}
The only change you need is wrapping the change in a new node at every update. If we merely consider persistence as a wrapper, we can make the implementation clean and concise.
My favorite operation on a persistent tree is the range copy. This is the ultimate version control technique one can pull off with regards to reverting a range back to a certain version. Imagine doing a range reset back to initial values - what a breakthrough! For a persistent tree, this can easily be achieved a few lines of code:
// revert range [a:b] of p
int rangecopy(int a, int b, int p, int revert, int L=0, int R=n-1) {
if (b < L || R < a) return p; // keep version
if (a <= L && R <= b) return revert; // reverted version
return newparent(rangecopy(a, b, l[p], l[revert], L, M),
rangecopy(a, b, r[p], r[revert], M+1, R));
}
In the usual tree, we change at most $O(log N)$ nodes. Therefore, for a persistent tree, we create at most $O(log N)$ nodes as well.
Persistence is a powerful tool, but can also be made simple. After reading this, I hope that you have come to understand persistent data structures in new light. Trust me, the conversion process is really simple since we just convert all assignment operators to new
leaves or parents.
Persistence is not only for segment trees - you can in fact use this technique for data structures BBSTs. By understanding persistence more generally, I hope you can find it easier to come up with your own code for range queries and even do lazy propagation. Feel free to comment on this thread to open discussion of such techniques.
As for other resources, you can check out Anudeep's blog for a more in-depth explanation of persistent trees, explained with problems to solve. With lots of practice, you can be ready hike your way to conquer next month's long challenge. Remember to stay persistent, and happy coding :)
Can anyone tell me why is it giving tle 1.01 although my approach is O(nlogn) Link-https://www.codechef.com/viewsolution/14248910
Problem link : contestpractice
Difficulty : Simple
Pre-requisites : Strings, KMP
Problem : Given two String A and B of the same length. You can do some (may be none) shift operations which results in the first character of B moving to the end. What is the minimum number of operations that are needed so that B has the longest common prefix with A.
At first, let's consider some partial solutions.
Just try implement the shift operations in O(N) and try all possible numbers of Shift operations on B. You properly even do not need write so much code if your language have some built-in library for string. You also do not have to do anything to speed up the string comparison. The overall complexity is O(N2).
Let's say we append string B at the end of string B. We get: B1,B2...BNB1,B2...BN. The thing worth noting is that after K shift operations we get BK+1,BK+2...BN,B1,B2...BK. This string(which we get after K shift operations) is now a substring of the new string that we got by appending B at the end of B.
So we'll now search all prefixes of A in B.B(means concatanation of B with B) which will help us in knowing which prefixes of A are present in B.B.
Let's say we have to search a string A of length M in a string B of length N. What we can do is generate hash of all substrings of B which are of length M and search for hash of string A in the generated hashes.
A hash function of string S could be say Summation[i=0 to length][26i*(S[i]-'a')] modulo some prime P. If we have the hash of a substring of length N say S[i,i+N], we can easily generate hash of S[i+1,i+N+1] by using inverse modulo since we are using a prime for modulo operations.
You need to know string matching algorithm KMP to get full points. You can learn KMP here, here, or anywhere you like to :).
KMP helps us in finding all prefixes of a string X in string Y. So we'll search A in B.B(means concatanation of B with B) which will help us in knowing which prefixes of A are present in B.B. We'll choose an answer that gives us the largest prefix, also it'll give the index at which that prefix matches, from which we can find the number of shifts required.
THANKS IN ADVANCE !!!!!
//JUST LIKE ANIMALS !!!!
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
bool ispalin(ll n){
ll i;
string s=to_string(n);
for(i=0;i<(s.length()/2);i++){
if(s[i]!=s[s.length()-1-i]){
return false;
}
}
return true;
}
int main(){
int t;cin>>t;
while(t--){
ll n,i;cin>>n;
if(n<10)cout<<n+1<<endl;
else
if(n%99==0&&n%11==0)cout<<n+2<<endl;
else{
for(i=n+1;;i++){
if(ispalin(i)==true)
{
cout<<i<<endl;break;
}
}
}
}
return 0;
}
How to find the next Palindrome using Greedy Algorithm? Input : 99 Output : 101
DEC16 long challenge was the first long challenge after i started taking competitive programming seriously. I want to know how to solve the problem SEAINCR from this challenge . The problems asks Q queries( Q <= 10^5) to find out the length of the longest increasing subsequence(LIS) from L to R indices in an array .
What i could manage till now :
Subtask 1 : 15 points (done using LIS in O(n^2) per query)
Subtask 2 : 15 points (done using LIS in O(nlogn) per query)
I could not solve the SUBTASK 3 : 70 points and I need the approach for that. I am familiar with fenwick trees(Binary Indexed Trees/BIT) as well as segment trees but i couldn't think of anything using them in this question.
First of all I want to say that this is a pretty dumb question but I cannot make the brute force solution for the OAK problem.
My approach is this:
I implemented this here https://www.codechef.com/viewsolution/14219647 but getting WA. If anyone has some time to give me an example were I'm mistaken I'll be forever grateful.
Thanks in advance.
Can any one share any simple approach for the problem chef and prime queries in in the June challenge
im unable to understand beatty sequence derivation,please help me.Please simple explanation for beatty sequence
when will we get the snackdown 2017 qualifer round certificates????
The program allocates 0.0M and takes 0.0s execution time. A lot of solutions are facing the same problem. Are the test cases fine? Or is there something which is not clearly mentioned in the question?
Author:Sudhanshu GuptaTester:Sudhanshu GuptaEditorialist:Sudhanshu Gupta
HARD
Math
For a given positive integer N find the number of all pairs (a, b) of positive integers such that 1 <= a < b <= N and the sum a + b divides the product a * b.
Solution can be found here.
I was solving XMAX question of Spoj using Gaussian elimination method to find the max subset xor of an array. But it's giving me WRONG answer after passing through few testcases,don't to why? Most surprisingly XORSUB question of Codechef(which is nearly same as XMAX, just have difference of initializing ans=0 and ans=k) is giving me Right answer on codechef.
Here are links:
XMAX question: http://www.spoj.com/problems/XMAX/.
My XMAX solution: http://ideone.com/UbRCH9
XORSUB question: https://www.codechef.com/problems/XORSUB.
My XORSUB solution: https://www.codechef.com/viewsolution/14208798
Kindly tell me some good sources to learn some programming theory which can be applicable for programming competitions.