My code compiles on my machine, however, it gets compilation error on CodeChef why so?
Why do i get a compile error?
SEBIHWY - Editorial
PROBLEM LINK:
Author:Istvan Nagy
Tester:Kevin Atienza
Translators:Sergey Kulik (Russian), Team VNOI (Vietnamese) and Hu Zecong (Mandarin)
Editorialist:Kevin Atienza
DIFFICULTY:
Cakewalk
PREREQUISITES:
Ad hoc
PROBLEM:
Sebi and his father are in a car, and they want to guess the speed of another car. Both cars travel at a constant speed, and the second is faster than the first car. There are markers on the highway every 50 meters.
They start a timer at the instant at which their car and the other car are parallel to each other. After $T$ seconds, they observe that both the cars are next to some markers and the number of markers between them is $D - 1$. The speed of Sebi's father's car is $S$.
Sebi and his father guess that the speed is $SG$ and $FG$, respectively. Determine who has the better guess.
QUICK EXPLANATION:
The correct speed of the other car is $S_{\text{other}} := S + \frac{180D}{T}$, in the right units. (Be careful: This speed isn't necessarily an integer.) Thus:
- If $|SG - S_{\text{other}}| < |FG - S_{\text{other}}|$, the answer is
SEBI
. - If $|SG - S_{\text{other}}| > |FG - S_{\text{other}}|$, the answer is
FATHER
. - If $|SG - S_{\text{other}}| = |FG - S_{\text{other}}|$, the answer is
DRAW
.
EXPLANATION:
To answer the problem, we need to compute the speed of the other car exactly. Let's denote that speed by $S_{\text{other}}$, in kph. If we can do this, then answering the problem boils down to computing which one has the "better guess": we compute the "error" of Sebi's and his father's guess as:
- $S_{\text{err}} = |SG - S_{\text{other}}|$
- $F_{\text{err}} = |FG - S_{\text{other}}|$
Then:
- If $S_{\text{err}} < F_{\text{err}}$, the answer is
SEBI
. - If $S_{\text{err}} > F_{\text{err}}$, the answer is
FATHER
. - If $S_{\text{err}} = F_{\text{err}}$, the answer is
DRAW
.
Computing $S_{\text{other}}$
We know how fast the first car travels, and that the second car is faster. Thus, we only need to know exactly how much faster the second car is than the first.
They start out in the same place, and then after $T$ seconds, they end up next to some markers. Since there are $D - 1$ markers between them, it means that after $T$ seconds, the cars are $50D$ meters away from each other. But the speeds of the cars are constant, which means this completely determines how much faster the second one is. Specifically, the second one is exactly $\frac{50D}{T}$ meters per second faster than the first!
Using this, and the fact that the first car has speed $S$ kph, we can simply add them to compute the speed of the second car, $S_{\text{other}}$. But we can't simply add them, because they are in different units! In order to add them properly and compare with $SG$ and $FG$, we need to convert $\frac{50D}{T}$ meters per second into kph. This can be done as follows:
$$\frac{\text{$50D$ m}}{\text{$T$ sec}} = \frac{\text{$50D$ m}}{\text{$T$ sec}} \frac{\text{$60$ sec}}{\text{$1$ min}} \frac{\text{$60$ min}}{\text{$1$ hr}} \frac{\text{$1$ km}}{\text{$1000$ m}} = \frac{\text{$180D$ km}}{\text{$T$ hr}}$$
This means that the second car is exactly $S_{\text{other}} := S + \frac{180D}{T}$ kph.
Here's an implementation: (in Python 3)
from fractions import Fraction as F
def solve():
s, sg, fg, d, t = map(int, input().strip().split())
actual = s + F(d*50*60*60, t*1000)
sdist = abs(sg - actual)
fdist = abs(fg - actual)
return 'SEBI' if sdist < fdist else 'FATHER' if sdist > fdist else 'DRAW'
for cas in range(int(input())):
print(solve())
Other possible problems
Here are a few possible bugs:
- We need to divide $\frac{180D}{T}$ exactly. This means the data type for $S_{\text{other}}$ should not be an integer. You could use, for example,
float
ordouble
. (The solution above uses fractions.) An alternative is to scale the speeds by $T$, so that they all become integers. Even if you use a
double
, you might still get an issue if you write your code as follows:double S_other = 180*D / T;
This is because even thoughS_other
is adouble
,D
andT
might not be, so180 * D / T
might round off unexpectedly. To avoid this, you can- declare
D
andT
to be doubles, or - use casting (
(double) 180 * D / T
), or - simply write it as
180.0 * D / T
. Note thatD / T * 180.0
might still fail. (Why?)
- declare
Time Complexity:
$O(1)$
AUTHOR'S AND TESTER'S SOLUTIONS:
Help Needed
Question : Utkarsh in Gardens
include<bits stdc++.h=""> using namespace std;
int main(){
int v,n;
cin>>v;
bitset<2005>c[2005];
for(int i=0; i<v; i++){
for(int j=0; j<v; j++){
cin>>n;
c[i][j] = n;
}
}
long long int ans=0;
for(int i=0; i<v; i++){
for(int j=i+1; j<v; j++){
n = (c[i]&c[j]).count();
ans += (n*(n-1))/2;
}
}
cout<<ans/2;
return 0;
}
Someone please explain the solution I will be very grateful. Thanks in advance.
help for january challenge question
[Closed] Help Needed
Question : Utkarsh in Gardens
include<bits stdc++.h=""> using namespace std;
int main(){
int v,n;
cin>>v;
bitset<2005>c[2005];
for(int i=0; i<v; i++){
for(int j=0; j<v; j++){
cin>>n;
c[i][j] = n;
}
}
long long int ans=0;
for(int i=0; i<v; i++){
for(int j=i+1; j<v; j++){
n = (c[i]&c[j]).count();
ans += (n*(n-1))/2;
}
}
cout<<ans/2;
return 0;
}
Someone please explain the solution I will be very grateful. Thanks in advance.
Sorting of vector of vectors.
Let there is a vector of vectors.vector< vector<int> > vec(n); Now if i write this sort(vec.begin(),vec.end()); How the sort function work on this please explain in detail.
Find the longest common prefix of some string Efficiently.
How to Find the longest common prefix of some string?
Doubt in CAPIMOVE problem
Please explain "During this time infection uses teleport one time and infect all the planets that can be achieved in one teleport jump". If the infection was on a planet no 2 and it is directly linked to 3, 4. So, would the teleport be stopped with planets directly connected to 2, 3, 4? Or just with 2?
How should I ask questions
I searched the previous questions on Codechef and found What kinds of questions can I ask here?. This provides us with what kind of questions to ask. But I would also like to get a better more detailed version of it with more specifics. For example, let us take Stack Overflow , it is a great Question and answers site for programmers because it has a well defined Help Center giving all the required details like what kind of questions should be asked, what should not be asked, how should I ask, and a lot more info for the users to follow. Now, I was unable to find such info on codechef.
I have been frequently encountering questions with " Getting wrong answer on < a question > . Here's my code. How to solve it ? ". Now I feel that this is not much of a great question ( atleast it's considered bad on Stack Overflow ). They should at least have given a bit more details. This question I found on codechef is related, but has not had any further movement Please frame questions properly
So I would like to ask for some guidance on how to ask good questions so that we know what sort of questions we can ask here, and following a few simple guidelines will help users ask questions which can be easily answered.
This would help us a lot. We are given the right to report ( or flag ) questions or answers, but there is no guidance on what should be reported and what not. The only questions I know should be flagged are questions relating to ongoing contests.
It would also be really helpful to have guidelines on voting, such as when to upvote or downvote.
I found a related link How to use this forum? , but that doesn't specify everything.
I found the question about comments When should I comment & when shouldn’t I ? , but admin just redirects us to Stack Overflow . I believe codechef should have it's own set of rules and regulations, like Stack Overflow's Help Center
So I request the moderators and admin to provide a good detailed Help Center for codechef like the one on Stack Overflow to help us improve the codechef discuss.
NOTE
I have searched Codechef to see if there is any guidance on this, but have not yet found it. If you know of this question beeing asked before, please feel free to mark this as a duplicate.
Create a Java program that will compute for the subject grade of a student based on the specification stated below
String [ ][ ] student= {{“Francis M. Reyes”,”92”,”89”,”93”,”94”},{“Joseph E. Estrada”,”80”,”70”,”81”,”78”},{“Ferdinand E. Marcos”,”77”,”93”,”83”,”90”},{“Cory C. Aquino”,”78”,”73”,”70”,”70”},{“Emilio A. Aguinaldo”,”78”,”86”,”78”,”80”},{“Ramon M. Magsaysay”,”91”,”81”,’’78”,”80”},{“Gloria M.Arroyo”,”84”,”74”,’’94”,”88”}};
Given the String array student having the initialization shown on the table above get the following:
GWA-General Weighted Average
Name of the student who obtained the highest GWA
Name of the student who obtained the lowest GWA
GWA=Prelim Grade 20% + Midterm Grade 20 % + Pre-final Grade 20% + Final Grade 40%
Name of the student who obtained the highest Prelim Grade
Name of the student who obtained the highest Midterm Grade
Name of the student who obtained the highest Pre-final Grade
Name of the student who obtained the highest Final Grade
Names of passing students (GWA>=75)
Names of failing students (GWA<75)
SAMPLE OUTPUT:
Francis M. Reyes GWA: 92.4
Joseph E. Estrada GWA: 77.4
Ferdinand E. Marcos GWA: 86.6
Cory C. Aquino GWA: 72.2
Emilio A. Aguinaldo GWA: 80.4
Ramon M. Magsaysay GWA: 82
Gloria M. Arroyo GWA: 85.6
Student with highest GWA: Francis M. Reyes
Student with Lowest GWA: Cory C. Aquino
Student with Highest Prelim Grade: Francis M. Reyes
Student with Highest Midterm Grade: Ferdinand E. Marcos
Student with Highest Pre-final Grade: Gloria M. Arroyo
Student with Highest Final Grade: Francis M. Reyes
List of Passing Students:
Francis M. Reyes
Joseph E. Estrada
Ferdinand E. Marcos
Emilio A. Aguinaldo
Ramon M. Magsaysay
Gloria M. Arroyo
List of Failing Students:
Cory C. Aquino
participate in Sintaxis-Experto
RGAME - Editorial
PROBLEM LINK:
Author:Abhra Dasgupta
Tester:Antoniuk Vasyl and Misha Chorniy
Editorialist:Pushkar Mishra
DIFFICULTY:
Easy-Medium
PREREQUISITES:
Ad Hoc, Observation
PROBLEM:
Given are $N+1$ numbers $A_0$ to $A_N$. These numbers come in as a stream in order from $A_0$ to $A_N$. The number coming in can be placed at either ends of the sequence already present. Score of such a gameplay is calculated as per given rules. Output the sum of scores of all possible different gameplays.
EXPLANATION:
Subtask 1
Subtask 1 can be solved by directly simulating the given problem. In other words, we can directly append the number coming in at either ends and check the sum for each possible arrangement. There can at maximum be $2^N$ different sequences. Therefore, the time complexity is $\mathcal{O}(2^N)$ per test case. This is sufficient for this subtask.
Subtask 2
Let us start by thinking of simpler sequences in which observing patterns could be easier. A trick is to take something like 1, 1, 1, ...., 1, 5 as the sequence. And then the 5 can be shuffled around to different positions to observe how many times a position is taken into account.
Nevertheless, we are going to take a more mathematical approach in this editorial. Let's see what happens when $k^{th}$ number, i.e., $A[k]$ appears in the stream. It can be appended to either of the two ends of the already existing sequence. But how many already existing sequence are there? Clearly, $2^{(k-1)}$. Let us say for now that $A[k]$ is appended to the right of already existing sequence. Now, consider some $p^{th}$ number $A[p]$ coming after $A[k]$. How many sequences exist such that the $A[p]$ will be multiplied by $A[k]$? For $A[p]$ to be multiplied by $A[k]$, all numbers coming in between these two must not go to the side that $A[k]$ is on, i.e., they should be put on the left in all the $2^{(k-1)}$ sequences where $A[k]$ has been appended on the right. If this happens, then when $A[p]$ comes, it will be multiplied by $A[k]$ when placed on the right of it. The $(p+1)^{th}$ up till $N^{th}$ numbers can be arranged in any order after that. So how many sequences in total will have the product of $A[k]$ and $A[p]$? Clearly, $2^{(k-1)}*2^{(N-p)}$. Thus, total value that gets added to the answer is $(A[k]*2^{(k-1)})*(A[p]*2^{(N-p)})$.
We now have a way to calculate the required answer. Below is the pseudocode of the same.
let possible_future_prod[i] = A[i] * 2^(N-i)
let answer = 0; //accumulator variable
for i = 0 to N-1
{
ways_to_arrange_prefix = 2^(i-1); //if i = 0, then 1
//multipying A[i] with the number of possible prefixes
partial_prod = (ways_to_arrange_prefix * A[i]);
//iterating over elements coming after i
for j = i+1 to N
{
total_prod = partial_prod * possible_future_prod[j];
//adding total_prod to the accumulator variable
ans += total_prod;
}
}
//recall, we had only taken the case when an element is
//appended to the right.
//for taking symmetrical cases into account, multiply by 2.
return 2*ans
This algorithm runs in $\mathcal{O}(N^2)$.
Subtask 3
The algorithm stated in subtask 2 can be made $\mathcal{O}(N)$ by precalculating the suffix sum of the $possible\_future\_sequences$ array. Once we have the $suffix\_sum$ array, the inner loop given above in the pseudocode can be reduced to:
//calculating the suffix_sum array
suffix_sum[n] = possible_future_prod[n]
for i = N-1 downto 0
suffix_sum[i] = possible_future_prod[i] + suffix_sum[i-1];
let answer = 0; //accumulator variable
for i = 0 to N-1
{
ways_to_arrange_prefix = 2^(i-1); //if i = 0, then 1
//multipying A[i] with the number of possible prefixes
partial_prod = (ways_to_arrange_prefix * A[i]);
//calculating the sum that can be achieved by
//multiplying A[i] with numbers coming after it
total_prod = (partial_prod * suffix_sum[i+1]);
//adding total_prod to the accumulator variable
ans += total_prod;
}
//for taking symmetrical cases into account, multiply by 2
return 2*ans
The editorialist's program follows the editorial. Please see for implementation details.
OPTIMAL COMPLEXITY:
$\mathcal{O}(N)$ per test case.
SAMPLE SOLUTIONS:
MCO16301 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
CAKEWALK
PREREQUISITES:
BRUTE FORCE
PROBLEM:
Find all possible reachable scores in a contest with subtasks.
EXPLANATION:
This is mainly an implementation problem. The first subtask is solvable with $O(n^2)$ brute force while the second subtask can be solved with bitmasks.
To solve the full problem, one way is to iterate through all integers from $0$ to $P - 1$, where $P$ is the product of all $x_{i}$. Then, we can repeated take $P$ modulo $x_{i}$ and divide it by $x_{i}$ to generate all $n$-tuples $(a_{1}, a_{2}, ..., a_{n})$ with $0 \le a_{i} \le x_{i} - 1$. Then, for each possibility, store the final score into a set and output the results.
Time Complexity : $O(x_{1}x_{2}...x_{n})$.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
MCO16302 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
EASY
PREREQUISITES:
Greedy
PROBLEM:
Find the maximum number of times a participant's score can overtake another participant in a contest.
EXPLANATION:
The idea of this problem is to use a greedy algorithm. The idea is you should always make the person with the least score currently submit. It can be proven that this gives the optimal result. Now, for the first subtask, we can simulate this process naively. For subtask 2, we can use a priority queue to keep track of the scores of each person and sort them in increasing order at all times.
Time Complexity : $O(nk log(nk))$
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
MCO16303 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
EASY
PREREQUISITES:
DYNAMIC PROGRAMMING
PROBLEM:
You start from $0$. Each step you can choose to go right by $a_{i}$ or left by $a_{i}$. What is the number of awys to end in $[l, r]$?
EXPLANATION:
Subtask $1$ can be solved in $O(2^{n} \cdot n)$ by trying all possible ways to perform the moves.
To solve subtask $2$, we let $dp[i][j]$ denote the number of ways to end in number $j$ after the $i$-th move. Now, the transition is $dp[i][j] = dp[i][j+a[i]] + dp[i][j-a[i]]$.
This solution works in $O(n \cdot Sum of a_{i})$ time.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
MCO16304 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
EASY-MEDIUM
PREREQUISITES:
TRIES
PROBLEM:
Given $n$ passwords and $q$ queries, find for each query the minimum number of keystrokes needed to key in a valid password.
EXPLANATION:
The first subtask can be solved in the naive way. For each string, we check all the possible passwords and find the minimum number of keystrokes needed to key in it from the the current string. Note that if the current string is $s$ and the password is $t$, then the minimum number of keystrokes needed is $|s| + |t| - 2lcp(s, t)$, where $lcp(s, t)$ is the longest common prefix of $s$ and $t$.
We need to optimize the current solution to solve Subtask $2$. The easiest way is to store the passwords in a trie, and for each query, we go down the trie. For each node of the trie, store the length of the word of the minimum length in the subtree. Now, we can find the answer in $O(Q + N)$ time where $Q$ is the sum of length of all query strings and $N$ is sum of length of all passwords. See the code for more details.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
MCO16305 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
MEDIUM
PREREQUISITES:
Tree DP, Small-to-Big Technique, DSU, LCA
PROBLEM:
Answer dynamic weighted distance query on a tree online. (Dynamic in this case means that we can add edges to the graph such that no cycles are formed)
EXPLANATION:
The first subtask can be done in $O(nq)$ by just simulating all the operations naively.
The second subtask can be solved in $O((n + q)\log n)$. The key is that in this subtask, we can just build the whole tree first and then answer all the distance queries. The tree distance queries on a static tree is a well-known problem and can be solved using Sparse Table and LCA for instance.
The third subtask is an extension of subtask $2$. Now, you have to answer the queries in real-time while the edges are being added. We will store a sparse table for each node denoting the $2^{k}$-th parent and the sum of all edges on the way to this parent. Now, when we join two vertices from distinct trees in the current forest, we will join the smaller tree to the larger tree and recalculate the sparse table for the smaller tree. You can see the details in the code. This allows us to solve the problem in $O((n + q)log^{2}n)$ time.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
MCO16306 - Editorial
PROBLEM LINK:
Author:Zi Song Yeoh
DIFFICULTY:
MEDIUM
PREREQUISITES:
DYNAMIC PROGRAMMING, SEGMENT TREES
PROBLEM:
Find the length of the longest alternating subsequence of a given sequence as well as the number of longest alternating subsequences.
EXPLANATION:
Subtask $1$ can be solved by iterating through all subsequences as usual.
Subtask $2$ can be solved using a simple dp. The idea is to let $dp[i][1]$ denote the longest alternating subquence ending at $i$ and the last element is larger than the second last element as well as the number of such subsequences. Define $dp[i][0]$ similarly except now the last element is smaller than the second largest element. Thus, we can form a simple recurrence for dp as in finding the longest increasing subsequence. For example, $dp[i][0] = \max_{a_{j} < a_{i}}(dp[j][1]) + 1$ and we can update the number of such subsequences by summing the number of subsequences stored in all $dp[j][1]$ that achieves the maximum value. This solution is $O(n^{2})$.
Subtask $3$ is just an extension of this idea. Iterating through all $j$ is inefficient. Instead, we can construct a segment tree where the $i$-th element stores the current dp value of this element. You can now transform the recurrence given in Subtask $2$ into a range query of the segment tree and we can update the corresponding element in the segment tree after each step. It is advisable to refer to the code for the details. The time complexity will be $O(n\log n)$.
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
RELATED PROBLEMS:
Runtime Error in SEACIR
Hi, I am getting run time error(NZEC). I should get a WA for this solution. Am I taking the input correctly or are interactive problems are handled in another way?
import sys
n, s, skip = map(int, input().split())
a = list(map(int, input().split()))
for _ in range(0,n):
r = int(input())
print(-1, -1)
sys.stdout.flush()
How to solve this problem based on strings and queries.
Can anyone explain how to solve this problem.