how exactly is penalty calculated in short contests?
penalty in short contest
Why does this code not cause a SIGSEGV?
Why does this code not cause a segmentation fault when it is supplied with input 1 1000?
#include <iostream>
#define MAX 1000
using namespace std;
long long dp[MAX] = {-1};
long long func(int n)
{
if(dp[n] > 0)
{
return dp[n];
}
else {
return dp[n] = (n * n) + func(n - 2);
}
}
int main()
{
dp[0] = 0;
dp[1] = 1;
dp[2] = 4;
int T;
cin >> T;
while (T--)
{
int n;
cin >> n;
cout << func(n) << endl;
}
return 0;
}
Internal Server Error in LTIME62 Forced Particles question
@admin I have been trying to submit solution for this problem for the past one day, but every time I'm getting internal server error on the submission result page!
repeating of staement
#include <stdio.h>
int main(void) { float bal,total; int amt; printf("enter the amount"); scanf("%d%f",&amt,&bal); if(amt%5==0 && amt<bal) { total=bal-amt; printf("the balance is=%f\n",total); } else { printf("you have entered the wrong text%f\n",bal); } return 0; }
why enter the amount statement is repeating with the output of result
QM10P5A editorial
PROBLEM LINK:
Author:Chandan Boruah
Tester:Taranpreet Singh
Editorialist:TaranPreet Singh
DIFFICULTY:
Simple
PREREQUISITES:
Greedy
PROBLEM:
Given N balls, each ball colored either red or blue, we have to find maximum number of green balls we can make. A Green ball can be made by merging consecutive red and blue ball.
QUICK EXPLANATION
- Final composition of balls would never have consecutive balls are red and blue, since we can always merge them to obtain one more green ball.
- So, merging balls greedily would generate maximum number of green balls.
EXPLANATION
All we need to do is to merge red and blue ball whenever we find a pair of such balls. All we need to prove now is that this approach is optimal.
Consider example: RBRB
Here, if we choose to merge second and third ball, our final compostion would look something like this RGB. Since we cannot move Green ball from in-between, we cannot merge the remaining red and blue ball. This proves that we should perform the merge operation as early as possible, otherwise Green ball might block future merge operation.
Instead of pair (2, 3), had we chosen (1, 2), we can still merge (3, 4) getting 2 green balls in the end, thus, being the optimal approach for merging.
Complexity:
Time Complexity is O(N).
AUTHOR'S SOLUTIONS:
using System;
using System.Collections.Generic;
class some
{
public static void Main()
{
int tests=int.Parse(Console.ReadLine());
for(int k=0;k<tests;k++)
{
int t=int.Parse(Console.ReadLine());
string s=Console.ReadLine();
int max=0;
int count=0;
for(int i=0;i<t-1;)
{
if(s[i]!=s[i+1]){count++;i+=2;}
else i++;
}
max=count;
count=0;
for(int i=1;i<t;)
{
if(s[i]!=s[i-1]){count++;i+=2;}
else i++;
}
max=Math.Max(count,max);
Console.WriteLine(max);
}
}
}
QM10P5B editorial
PROBLEM LINK:
Author:Chandan Boruah
Tester:Taranpreet Singh
Editorialist:TaranPreet Singh
DIFFICULTY:
Easy
PREREQUISITES:
Slope of a line, Observation.
PROBLEM:
Given $N$ lines represented by two points, we need to find maximum number of lines which can pass through a single point, without superimposing any other line. we can move any line but not rotate it.
QUICK EXPLANATION
- Represent lines as pair $(m, c)$ where line can be given as $y = mx+c$, called line slope form. We can now see that we can change the $c$ for any line, but cannot modify $m$.
- Lines with Same value of slope ($m$) are parallel to each other, given ($c_{1} \neq c_{2}$).
- No two parallel lines can pass through same point without superimposing each other.
- Our problem reduces to finding different values of slopes from the given set of lines.
EXPLANATION
The quick Explanation says it all. :-)
We can calculate slope of a line as $(y_2 - y_1)/(x_2-x_1)$, add them to a set and count the number of distinct values of slope in set.
BUT BUT, what about REs we were getting in contest??
This was because of some lines having $x_1 = x_2$, test case specially added by devil tester :D, which caused arithmetic Division by zero error.
We need to handle vertical (and probably horizontal too, if we wish) lines separately. Maybe having two boolean values horizontal and vertical would do fine. Each boolean value indicate whether input set contains a vertical (or horizontal) line.
If true, would each of them contribute 1 to final answer.
Complexity:
Time Complexity is $O(N)$.
AUTHOR'S SOLUTIONS:
using System;
using System.Collections.Generic;
class some
{
public static void Main()
{
int t=int.Parse(Console.ReadLine());
while((t--)>0)
{
int n=int.Parse(Console.ReadLine());
int[]x1=new int[n];
int[]y1=new int[n];
int[]x2=new int[n];
int[]y2=new int[n];
for(int i=0;i<n;i++)
{
string[]ss=Console.ReadLine().Split();
x1[i]=int.Parse(ss[0]);
y1[i]=int.Parse(ss[1]);
x2[i]=int.Parse(ss[2]);
y2[i]=int.Parse(ss[3]);
}
SortedSet<double>slopes=new SortedSet<double>();
for(int i=0;i<n;i++)
{
double slope=0;
if(y1[i]==y2[i])
{
slope=int.MaxValue;
}
else
slope=(x1[i]-x2[i])*1.0/(y1[i]-y2[i]);
if(!slopes.Contains(slope))
{
slopes.Add(slope);
}
}
Console.WriteLine(slopes.Count);
}
}
}
A Learning Module for Beginners (Currently in Development, Feedback requested)
Hi fellow programmers,
We are planning to create a course for beginners. Beginners often come to the site and got overwhelmed by so many problems present on the site. Many of them often ask where to start from. So, we thought of creating a course module for them. The module will be a set of tutorials and a set of practice contests on CodeChef.
For this module, we will identify the key set of topics that a beginner should solve in order to reach a certain level. For each topic, we will have some 5 to 10 or more problems on that topic that she should solve. I have collected some set of problems for following topics (in increasing order of the difficulty). Please feel free to give any relevant feedback, suggest some problems that you think can be added or removed. Any suggestions regarding would be most welcome.
Note that currently, this module is not ready. It's still work in progress. I have marked this post a community wiki. Please feel free to edit it.
Module #0: What's competitive programming?
Competitive Programming is a mind sport where participants solve problems by writing code. The problems in question are typically logical, mathematical or algorithmic in nature. Participants must write code according to given specifications which typically includes a pre-specified time and memory limits within which a program must successfully complete execution.
Two of the most prominent competitive programming competitions are the ACM International Collegiate Programming Competition (ICPC) and the International Olympiad of Informatics (IOI) which are for univeristy and high school students respectively. The ICPC is one of the oldest, largest, hardest and most prestigious programming competitions in the world, and it is widely considered as the "Olympics" of programming.
Some other prominent programming competitons are
- Google Code Jam
- Facebook Hackercup
- Topcoder Open (TCO) Algorithm
- Yandex Algorithm
Apart from the above, regular programming competitions are conducted on various platforms across the intetnet. Some of these are
- Codechef
- Codeforces
- Hackerrank
- Topcoder
- Hackerearth
- Atcoder
- CSAcademy
Getting started with CodeChef platform
- Solving your first problem in C on CodeChef: https://www.youtube.com/watch?v=qM-TzG3dkcc
- Solving your first problem in C++ on CodeChef https://www.youtube.com/watch?v=fm7tTWy-H-E
- Solving your first problem in Java on CodeChef https://www.youtube.com/watch?v=gaPdjwuFZTs
- Common programming mistakes at Codechef.: https://www.youtube.com/watch?v=VmvGfVadOoU What sort of errors do you encounter and what they mean?
- Must check: https://www.codechef.com/getting-started
Module #1: Learning A Programming Language
Check https://www.codechef.com/ioi/basics, the section "Language Constructs - C++ - 1" for basic knowledge of C++. If you want to learn basics of other languages like Java, Python, you can refer to (need to provide more links).
Just get it done :) Starting questions to do
- FLOW001 (add two numbers)
- FLOW002 (find reminder of a number when divided by other number)
- TEST (one of the starting problem to solve on CodeChef)
- INTEST (for testing whether your input/output routines are fast enough)
Basic knowledge of if/else conditions
- FLOW010 (basic knowledge of if/else conditions)
- FLOW014 (another if/else knowledge question)
- LADDU (very nice implementation problem to solve)
Dealing with numbers
- FLOW002 (find remainder of a number a % b)
- FLOW004 (find sum of first and last digit of a number)
- FLOW006 (find sum of digits of a number)
- FLOW007 (given a number, reverse it)
- FCTRL (an interesting question, must solve)
Basic knowledge of arrays
- LECANDY
- TEMPLELA (contains some interesting corner cases)
- RAINBOWA (basic knowledge of arrays)
- COPS (requires bit of creativity :) )
- VILTRIBE
Working with strings
- NITIKA (reading strings, and string related formatting)
- GOODBAD (ASCII characters, lower-case and uppercase characters)
- FLOW015 (checks basic knowledge of strings and calendar)
- FRGTNLNG (very nice question to test input processing skills)
- LAPIN (check whether a string is a palindrome or not)
- CSUB (good for understanding notion of substrings)
Handling floating point numbers
Off to recursion
- INTRN080 (Ackermann function)
- NOKIA (a nice question to solve)
- TRISQ (writing recurrence relations and solve them using recursion)
- Another way to implement Ackermann function without stack overflow. Will give people idea of what's stackoverflow error.
- SUMTRIAN: See the tutorial at https://www.codechef.com/wiki/recursion-sums-triangle, Its recursion with memoization.
Provide Few More Implementation Problems:
Space and time complexity of a program
Module #2: (Basic Mathematics)
Please see https://www.codechef.com/ioi/basics, Mathematics section for very basic mathematics.
Basic Number Theory:
- FLOW016 (find gcd and lcm)
- CATSDOGS
- FCTRL
- FCTRL2 (decimal representation): https://www.codechef.com/wiki/tutorial-small-factorials
- CKISSHUG (exponentiation)
- CHMOD (exponentiation)
- LEVY (sieve)
- NPL1701C (sieve)
- JMAGNUM (sieve)
- KPRIME (sieve)
- CDQU1 (prime sieve)
- CDQU3 (factorization)
- https://www.codechef.com/OCT09/problems/H4/,https://www.codechef.com/wiki/tutorial-just-simple-sum (bit intermediate level)
Module #3: Sorting algorithms
- TSORT
- MRGSRT (merge sort. It’s highly recommended that you don’t use library and code your own merge sort, quick sort algorithms to test your skills in this problem)
- SIMPSTAT (a very basic sorting problem)
- KOL16J (check whether the array is sorted)
- HORSES (another very simple problem)
- GEEK01 (find median of a given matrix)
- STICKS
- INCPR04
- PERMEXIS (similar question to the above)
- ORDTEAMS (learn how to use comparison function in sorting by having a look at https://www.codechef.com/wiki/using-constructors-and-comparators-c)
- OPTCODE (another problem requiring comparison functions, learning how to use pair<int, int=""> in C++)
- REL102 (nice simple sorting problem)
Module #4: Greedy Algorithms
- MAXDIFF (basic greedy problem)
- CHEFST
- TACHSTCK (important to understand proof of the solution, you can learn the trick of how if swap the optimal solution, will the solution get worse only?)
- CDX1604 (sorting with gredy observations)
- STICKS
- MANYCHEF
- KNPSK (interesting version of knapsack problem with weights = 1 or 2)
- CHEFTMA
- TADELIVE (really nice greedy level problem)
- LEMUSIC
- FGS
- LUMPYBUS
- CLETAB (nice greedy problem to do)
- MMPROD
Module #5: Stacks and Queues
Stack:
- COMPILER
- ONP (reverse polish notation)
- TSECJ104
- THESAV
- TE3N
- BEX
- DCGAME(intermediate)
- HISTOGRA spoj (either we will make its clone on CodeChef or a similar CodeChef problem can be used.)
Queue:
Module #6: Binary Search:
- FORESTGA (very nice question)
- CHEFHCK2
- SNAKEEAT
- RIGHTTRI
- ASHIGIFT
- SNTEMPLE (much recommended)
- LOWSUM (much recommended)
- SCHEDULE
- kayaks (a must solve question for intermediate level)
- STACKS
- DIVSET (greedy with binary search)
- ELHIDARR (extension of a popular question on interviews. Must solve Question)
- BASE (very nice binary search problem, requires bit of mathematics, must solve)
Module #7: Basic Dynamic Programming
- ALTARAY (basic dp problem)
- SUMTRI (very nice and basic dp problem)
- DBOY (very nice dp problem, must do)
- XORSUB (basic 2-D dp)
- STRMRG (a variation of standard LCS (longest common subsequence) problem, must do problem)
- GRID (simple 2-D dp, prefix/suffix sums over a 2-D matrix, must do)
- STRSUB (dp with binary search)
Module #8: Basic Graph Theory
Depth first search
- FROGV (can also be done without requiring dfs by making some simple observations, in fact, dfs is overkill for it)
- FIRESC (must do dfs problem, can also be done using union-find algorithm)
- CHFNFRN (check whether a graph is bipartite)
- FRIEMEET
- DIVIDE (binary search with bipartite checking type logic)
- MCO16104 (consider the inverse graph)
- AUEC (existence of euler circuit in a graph)
Breadth first search
- CHFNFRN (check whether a graph is bipartite)
- DIGJUMP (a great problem with one of the great editorials)
- SNGRAPH (a tricky bfs)
- SNSOCIAL
- CHEFARC
- MCO16104 (can also be solved using bfs)
- L56LABY
Union Find
- BIGOF01 (very basic problem on union find, must do)
- COLGQU (slight harder version on union find)
- DISHOWN
- CHFNFRN (check whether a graph is bipartite)
- MTRWY (slight harder version on union find)
- JABO
- FILLMTR (very nice problem on union find, intermediate level, you may also check the video tutorials)
- GALACTIK (a very nice union find problem)
- PARITREE (intermediate level problem)
- SETELE (much recommended problem)
- MAGICSTR (recommended only for intermediate+ level)
Advanced features of languages
Check Language Constructs. It's good to learn Standard Template Library (STL) - C++ 2 section in https://www.codechef.com/ioi/basics for reading.
Can anyone be blamed for plagiarism in Practice Questions ?
After contests are over, I do look at solutions of other coders and try understand and and improve solutions for lower time..... Can I be warned / banned in this case ?
Why is my solution is wrong for practice Question FLOW006
include<stdio.h>
main() { int t,i,n,sum=0; scanf("\n%d",&t); for(i=0;i<t;i++) { scanf("%d",&n); sum=0; while(n!=0) { sum=sum+n%10; n=n/10; } printf("\n%d",sum); } return 0; }
how many approx loops are allowed in 2.5 sec lime limit
How many approx loops can be traversed in 2.5 sec? And what should be best complexity to traverse 10^6?
Is Code Chef a competitive site or can I learn to code also here?
I am new to coding and in search of online certification courses in Coding and Programming. So is this a site for me?
Need help to find out why my approach is failing for RECTSQ
Hi
I was trying to solve the problem RECTSQ, and somehow succeeded to solve it for the provided testcases, but codechef shows WA. Please help me to find the flaws in my approach or concept.
Since the squares must be of same dimensions, i understand that i have to maximize their side so the no of squares would be minimal.So, what i have done is:
1. Find the smallest of the dimensions from the rectangle data(consider as @varsmall
), since the side of the square cant be greater than any of the dimensions.
2. Keep looping from 'small' upto 2, because i thought looping upto 1 would create the maximum no of squares.
3. for each 'i' in the for loop, I check if the 'i' nearest to 'small' can create a square which perfectly divides the area and 'break' if it does, as that 'i' would be the greatest square possible.
for (int i = small; i greaterthanequals 2; i--) {
if (area % (i * i) == 0) {
noOfSquares = area / (i * i);
break;
}
}
This is everything. Here's the code.Thanks in advance.
javascript on macbook
Hi guys I have been trying javascript language on macbook sometimes some codes don't work. such as substituting names for some id elements. when I click the button click for greeting nothing comes up! I have checked if I used the right language so there are no syntax errors This for example doesn't work on my mac: <head> </head> <body>
Enter your name: <input type="text" id="namebox" size="12" value="">
<input type="button" value="click for greeting" onlclick="document.getElementById('outputDiv').innerHTML='hello'+ document.getElementById('namebox').value +', welcome to Mido's website!<br>do you mind if we call you' + document.getElementById('namebox').value + '?';" >="" <hr=""> </body>why is this wrong? Re
#include<iostream>
using namespace std;
int main(){
int n,a[100];
cin>>n;
for(int i=0;i<n;i++){
int fact=1;
cin>>a[i];
for(int j=1;j<a[i]+1;j++)
fact = fact*j;
a[i]=fact;
}
for(int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
Invitation to CodeChef August Long Challenge 2018 sponsored by ShareChat!
Hello CodeChef Community!
We are thrilled to invite you to participate in the August Long Challenge 2018 sponsored by ShareChat. In addition, there are some exciting internship and full-time job opportunities by ShareChat for Indian programmers in the August Long Challenge 2018. For more details, you may visit the contest page. I hope you will join your fellow programmers and enjoy the contest problems. Joining me on the problem setting panel are:
- Problem Tester: famafka (Mark Mikhno)
- Problem Authors: likecs (Bhuvnesh Jain), vidyut_1 (Ashesh Vidyut), step_by_step (Stepan Filippov), pieguy (David Stolp), allllekssssa (Aleksa Plavsic), bciobanu (Bogdan Ciobanu), sanroylozan (Aron Noszaly), jitendersheora (Jitender Sheoran), dpraveen (Praveen Dhinwa)
- Problem Editorialist: likecs (Bhuvnesh Jain)
- Statement Verifier: xellos0 (Jakub Safin)
- Russian Translator: gomelfk (Fedor Korobeinikov)
- Mandarin Translator: huzecong (Hu Zecong)
- Vietnamese Translator: VNOI Team
- Hindi Translator: sriand (Srijan Dubey)
Contest Details:
Time: 3rd August 2018 (1500 hrs) to 13th August 2018 (1500 hrs). (Indian Standard Time — +5:30 GMT) — Check your timezone.
Contest link:www.codechef.com/AUG18
Registration: You just need to have a CodeChef handle to participate. For all those, who are interested and do not have a CodeChef handle, are requested to register in order to participate.
Getting started here, questions about strategy, etiquitte, etc.
Hi guys.
I've just started here, I have a few questions about how I approach this place. Firstly, let me just say that wow - some of the problems here are pretty difficult, even for easy!
Alright, so I've just bunch of the questions in the FAQ, here's a few more.
What's the etiquette for posting here? For example are 'I'm working XYZ practice problem, I've got TLE error, here's my code, what should I do?' questions ok?
What's the general strategy for solving problem, or doing time optimization? Are there any tools that you use? Like, one of the things I can see that would be problematic, is when you get a 'wrong answer' but you don't know what the 'expected vs output' is. Is this just something you need to deal with as a programmer, to think of the corner cases yourself?
Is there any way to get additional test data?
How do you organise your code chef files in your IDE? For example, your class name (in Java) must called Main, and it can't be part of any package, when you paste in to the submitter, otherwise it'll give you an error, wondering how people deal with that.
code reusablity - I get the feeling that a lot of this is going to be using various appropriate algorithms. What I would tend to do is import the package that contains the algorithm. But given that the submission has to be a single file with no non-native imports, is the only thing you can do, is copy the code in for each algorithm?
Where would you start in terms of first problems to solve? For example I would suggest doing the Enormous Input test as one of your first problems.
.
PRMDIV - Editorial
Problem Link
Author:Ivan Fekete
Tester:Misha Chorniy
Editorialist:Bhuvnesh Jain
Difficulty
EASY
Prerequisites
Sieving Techniques
Problem
Let $S(x)$ denote the sum of distinct prime divisors of $x$. Find the number of pairs $(i, j)$ in array $A$ such that if $A[i]$ divides $A[j]$ then $S(A[i])$ also divides $S(A[j])$.
Explanation
Let us first calculate the function $S$ for all integers efficiently. This is a simple modification of the prime sieve where we add the contribution each prime divisor to the numbers as well.
S[1] = 0
for i in [2, 1000000]:
if S[i] == 0:
# number is prime
j = i
while j <= 1000000:
S[j] += i
j += i
The time complexity of the above approach will be $O(\sum_{p = prime} X/p) = O(X \log{\log{X}})$, where $X = 1000000$.
Let us also calculate the good pairs of numbers. Below is a pseudo-code for it:
# good[i] stores the "j" such that
# "i" and "S[i]" divide "j" and "S[j]" respectively.
for i in [2, 1000000]:
j = i
while j <= 1000000:
# Ensured that "i" divides "j". See the loop conditions.
if S[j] % S[i]:
good[i].append(j)
j += i
The time complexity of the above approach is $O(\sum_{i=2}^{i=N} X/i) = O(X \log{X})$, where $X = 1000000$. If you have any doubts regarding the above 2 precomputations, I suggest you to learn and read Sieve of Eratosthenes and try to understand how the code is modified here.
Now, coming back to the problem. We need to find the number of pair of $(i, j)$ in array $A$ such that if $A[i]$ divides $A[j]$ then $S(A[i])$ also divides $S(A[j])$. For this, if we do it naively for every pair using the help of above pre-computation to check if $A[i]$ and $A[j]$ is good, then it will inefficient and only pass subtask 1.
The important thing to note that even if we iterate over all "good" arrays, the total size of all arrays is bounded by $O(X \log{X})$, considering all the numbers are appended. Actually, this bound is lower, but it doesn't matter.
So, let say if we have the frequency of all elements in the array $A$. When iterating over the "good" array, if $2$ numbers have frequency $x$ and $y$ then they contribute $(x * y)$ to the answer. The only caveat is that pair $(i, i)$ i.e. same pair of indices is also counted in it. So, we need to subtract $N$ from the final answer as well.
Thus, the below psuedo-code can easily solve our complete problem:
for i in [1, n]:
freq[a[i]] += 1
ans = 0
for i in [2, 1000000]:
if freq[i] > 0:
# Element is present
for j in good[i]:
ans += freq[i] * freq[j]
# Account for i == j
ans -= n
print ans
# Clear freq array for next test case.
for i in [1, n]:
freq[a[i]] -= 1
Once, you are clear with the above idea, you can see the editorialist implementation below for help.
Feel free to share your approach, if it was somewhat different.
Some Thoughts
There exist a linear sieve for prime numbers as well. Can you modify the first algorithm for pre-computation of $S$ to work in linear time? If yes, how? If no, what is your counter argument?
Time Complexity
$O(X \log{X} + N)$ per test case.
Space Complexity
$O(X \log{X})$
AUTHOR'S AND TESTER'S SOLUTIONS:
Author's solution can be found here.
Tester's solution can be found here.
Editorialist's solution can be found here.
execution time taken by methods
how can i calculate the execution time of each methods in my program . if my method is calling some other method then it should tell the execution time of current method along with the method that is being called inside current method.
Campus Chapter
hii good morning sir/mam i want to ask some queries related to campus chapter.
1-My college students are very new to competitive programming so for first few contests can you host some easy contests??
2- I don't have college website in that case what we can do?
3- How we can invite guest lectures for coding in our college
Wrong solution for problem KMXOR
for problem "https://www.codechef.com/problems/KMXOR", I am getting wrong answer
My solution: https://www.codechef.com/viewsolution/19707356
Can somone please tell what is wrong in my solution since am unable to figure out?
Thanks