Basic programming (Part 1)

10 238 0
Basic programming (Part 1)

Đang tải... (xem toàn văn)

Thông tin tài liệu

Some ways to avoid runtime errors: 1) Make sure you arent using variables that havent been initialized. These may be set to 0 on your computer, but arent guaranteed to be on the judge. 2) Check every single occurrence of accessing an array element and see if it could possibly be out of bounds. 3) Make sure you arent declaring too much memory. 64 MB is guaranteed, but having an array of size 100000 100000 will never work. 4) Make sure you arent declaring too much stack memory. Any large arrays should be declared globally, outside of any functions, as putting an array of 100000 ints inside a function probably wont work.

Basics of Input/Output The very first step of getting started with online judge is to understand: • • How to read input data? How to output the answer? Input data is read from standard input stream (STDIN) and results are printed to standard outputstream (STDOUT) Most of the questions will deal with either integers or strings An example C code to read an integer from STDIN and printing it out to STDOUT is shown below #include int main() { int n; scanf("%d",&n); //read input integer from STDIN printf("%d",n); //print output integer to STDOUT return 0; } Sample code snippet to read integer for all other languages are given in the code editor below An example C code to read a string from STDIN and printing it out to STDOUT #include int main() { char a[100]; //assuming that string size will not exceed 100 scanf("%s",a); //read a string in array a printf("%s",a); //print out array a return 0; } Careful not to print any thing else in the output, such as printf("The answer is %d",n); because the online judge directly compares your output to expected output like normal string comparison Say if expected output is 5, and the code prints The answer is then when online judge compares with The answer is 5, it will say that the code produced wrong result Every HackerEarth problem has a predefined input and output format Every problem will also have Constraints section which helps in determining what size of array to be created or what datatypes to use, say int or long long Runtime Errors While solving the problems on an online Judge, many runtime errors can be faced, which are not clear by the message which comes with them Lets try to understand these errors To get clear about the definition of run time error: A runtime error means that the program was compiled successfully, but it exited with a runtime error or crashed You will receive an additional error message, which is most commonly one of the following: 1) SIGSEGV This is the most common error, i.e., a "segmentation fault" This may be caused e.g by an out-of-scope array index causing a buffer overflow, an incorrectly initialized pointer, etc This signal is generated when a program tries to read or write outside the memory that is allocated for it, or to write memory that can only be read For example, you’re accessing a[-1] in a language which does not support negative indices for an array 2) SIGXFSZ "output limit exceeded" Your program has printed too much data to output 3) SIGFPE "floating point error" This usually occurs when you’re trying to divide a number by 0, or trying to take the square root of a negative number 4) SIGABRT These are raised by the program itself This happens when the judge aborts your program in the middle of execution Due to insufficient memory, this can be raised 5) NZEC (non-zero exit code) - this message means that the program exited returning a value different from to the shell For languages such as C/C++, this probably means you forgot to add "return 0" at the end of the program It could happen if your program threw an exception which was not caught Trying to allocate too much memory in a vector For interpreted languages like Python, NZEC will usually mean that your program either crashed or raised an uncaught exception Some of the reasons being in such cases would be: the above mentioned runtime errors Or, for instance usage of an external library which is causing some error, or not being used by the judge 6) MLE (Memory Limit Exceeded) This error means that your program tried to allocate memory beyond the memory limit indicated This can occur if you declare a very large array, or if a data structure in your program becomes too large 7) OTHER This type of error is sometimes generated if you use too much memory Check for arrays that are too large, or other elements that could grow to a size too large to fit in memory It can also be sometimes be generated for similar reasons to the SIGSEGV error Some ways to avoid runtime errors: 1) Make sure you aren't using variables that haven't been initialized These may be set to on your computer, but aren't guaranteed to be on the judge 2) Check every single occurrence of accessing an array element and see if it could possibly be out of bounds 3) Make sure you aren't declaring too much memory 64 MB is guaranteed, but having an array of size [100000] * [100000] will never work 4) Make sure you aren't declaring too much stack memory Any large arrays should be declared globally, outside of any functions, as putting an array of 100000 ints inside a function probably won't work Time and Space Complexity Sometimes, there are more than one way to solve a problem We need to learn how to compare the performance different algorithms and choose the best one to solve a particular problem While analyzing an algorithm, we mostly consider time complexity and space complexity Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input Similarly, Space complexity of an algorithm quantifies the amount of space or memory taken by an algorithm to run as a function of the length of the input Time and space complexity depends on lots of things like hardware, operating system, processors, etc However, we don't consider any of these factors while analyzing the algorithm We will only consider the execution time of an algorithm Lets start with a simple example Suppose you are given an array AA and an integer xx and you have to find if xxexists in array AA Simple solution to this problem is traverse the whole array AA and check if the any element is equal to xx for i : to length of A if A[i] is equal to x return TRUE return FALSE Each of the operation in computer take approximately constant time Let each operation takes cc time The number of lines of code executed is actually depends on the value of xx During analyses of algorithm, mostly we will consider worst case scenario, i.e., when xx is not present in the array AA In the worst case, the if condition will run NN times where NN is the length of the array AA So in the worst case, total execution time will be (N∗c+c)(N∗c+c) N∗cN∗cfor the if condition and cc for the return statement ( ignoring some operations like assignment of ii ) As we can see that the total time depends on the length of the array AA If the length of the array will increase the time of execution will also increase Order of growth is how the time of execution depends on the length of the input In the above example, we can clearly see that the time of execution is linearly depends on the length of the array Order of growth will help us to compute the running time with ease We will ignore the lower order terms, since the lower order terms are relatively insignificant for large input We use different notation to describe limiting behavior of a function OO-notation: To denote asymptotic upper bound, we use OO-notation For a given function g(n)g(n), we denote by O(g(n))O(g(n))(pronounced “big-oh of g of n”) the set of functions: O(g(n))=O(g(n))= { f(n)f(n) : there exist positive constants cc and n0n0 such that 0≤f(n)≤c∗g(n)0≤f(n)≤c∗g(n) for all n≥n0n≥n0 } ΩΩ-notation: To denote asymptotic lower bound, we use ΩΩ-notation For a given function g(n)g(n), we denote by Ω(g(n))Ω(g(n))(pronounced “big-omega of g of n”) the set of functions: Ω(g(n))=Ω(g(n))= { f(n)f(n) : there exist positive constants cc and n0n0 such that 0≤c∗g(n)≤f(n)0≤c∗g(n)≤f(n) for all n≥n0n≥n0 } ΘΘ-notation: To denote asymptotic tight bound, we use ΘΘ-notation For a given function g(n)g(n), we denote by Θ(g(n))Θ(g(n))(pronounced “big-theta of g of n”) the set of functions: Θ(g(n))=Θ(g(n))= { f(n)f(n) : there exist positive constants c1,c2c1,c2 and n0n0 such that 0≤c1∗g(n)≤f(n)≤c2∗g(n)0≤c1∗g(n)≤f(n)≤c2∗g(n) for all n>n0n>n0 } Time complexity notations While analysing an algorithm, we mostly consider OO-notation because it will give us an upper limit of the execution time i.e the execution time in the worst case To compute OO-notation we will ignore the lower order terms, since the lower order terms are relatively insignificant for large input Let f(N)=2∗N2+3∗N+5f(N)=2∗N2+3∗N+5 O(f(N))=O(2∗N2+3∗N+5)=O(N2)O(f(N))=O(2∗N2+3∗N+5)=O(N2) Lets consider some example: int count = 0; for (int i = 0; i < N; i++) for (int j = 0; j < i; j++) count++; Lets see how many times count++ will run When i=0i=0, it will run 00 times When i=1i=1, it will run 11 times When i=2i=2, it will run 22 times and so on Total number of times count++ will run is 0+1+2+ + (N−1)=N∗(N−1)20+1+2+ +(N−1)=N∗(N−1)2 So the time complexity will be O(N2)O(N2) int count = 0; for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; This is a tricky case In the first look, it seems like the complexity is O(N∗logN)O(N∗logN) NN for the j′sj′s loop and logNlogN fori′si′s loop But its wrong Lets see why Think about how many times count++ will run When i=Ni=N, it will run NN times When i=N/2i=N/2, it will run N/2N/2 times When i=N/4i=N/4, it will run N/4N/4 times and so on Total number of times count++ will run is N+N/2+N/4+ +1=2∗NN+N/2+N/4+ +1=2∗N So the time complexity will be O(N)O(N) The table below is to help you understand the growth of several common time complexities, and thus help you judge if your algorithm is fast enough to get an Accepted ( assuming the algorithm is correct ) Length of Input (N) Worst Accepted Algorithm ≤[10 11]≤[10 11] O(N!),O(N6)O(N!),O(N6) ≤[15 18]≤[15 18] O(2N∗N2)O(2N∗N2) ≤[18 22]≤[18 22] O(2N∗N)O(2N∗N) ≤100≤100 O(N4)O(N4) ≤400≤400 O(N3)O(N3) ≤2K≤2K O(N2∗logN)O(N2∗logN) ≤10K≤10K O(N2)O(N2) ≤1M≤1M O(N∗logN)O(N∗logN) ≤100M≤100M O(N),O(logN),O(1)O(N),O(logN),O(1) Basics of Implementation Questions that are based on ad-hoc ideas and brute-force solutions are usually classified under the implementation category The objective of such questions is to help users to improve their ability of converting English statements into code implementation This tutorial discusses kinds of problems that will help you get started with such questions Question You are given two numbers NN and MM, print the absolute difference between two numbers i.e |N−M||N−M| Approach: • • Store the difference of NN and MM in a temporary variable result Check if the value of result is negative The question is to print the absolute difference Therefore, if the value is negative, then make it positive by multiplying it with −1−1 • Print out the value of result • Implementation #include using namespace std; int main() { int n, m; // Read the two numbers from STDIN cin >> n >> m; // Store the difference between them in result int result = n - m; // If result is negative multiply it with -1 if(result < 0) { result = result*(-1); } // Print the result to STDOUT cout > s; int s_len = s.length(); // Iterate over each character in the string for(int j=0; j

Ngày đăng: 20/10/2016, 09:35

Từ khóa liên quan

Mục lục

  • Basics of Input/Output

  • Time and Space Complexity

  • Basics of Implementation

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan