SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
ACM Aleppo CPC Training
Part 1 C++ Programming Concepts
By Ahmad Bashar Eter
About the contest and the training
• What is the ACM ICPC?
• Who this contest is for?
• What will I get from this contest?
About the contest and the training
• What should I do to win in this contest?
• Who this training is for?
• How far I will reach in programming contest word after this part is
finished?
The Problems
Each problem has:
• Problem description
• Input description
• Output description
• Sample input (1 or more)
• Sample output (1 or more)
Judge Response
• Accepted
• Wrong Answer
• Time Limit Exceeded
• Runtime Error
• Compilation Error
• Presentation Error
Example 1
HQ9+ is a joke programming language which has only four one-character instructions:
"H" prints "Hello, World!",
"Q" prints the source code of the program itself,
"9" prints the lyrics of "99 Bottles of Beer" song,
"+" increments the value stored in the internal accumulator.
Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of
the program which are not instructions are ignored.
You are given a program written in HQ9+. You have to figure out whether executing
this program will produce any output.
Input
The input will consist of a single line p which will give a program in HQ9+. String p will
contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will
be between 33 (exclamation mark) and 126 (tilde), inclusive.
Output
Output "YES", if executing the program will produce any output, and "NO" otherwise.
Solve at: http://codeforces.com/problemset/problem/133/A
Self Training resources
• First of all Google and Wikipedia.
• To ask a question go to www.stackoverflow.com
• C++ and STL libraries reference: www.cplusplus.com
• C++ tutorials: www.learncpp.com
• Online Judges:
Code Forces
UVA
A2OJ
Top Coder
SPOJ
Hacker Earth
Self Training resources
Books:
1. Programming Challenges
2. Competitive Programming 3
Tutorials:
Topcoder tutorials:
Hacker Earth Code Monk
GeeksForGeeks.org
C++ Review
Variables & Data types
• To define a variable: [TypeName] [VariableName];
• Integer data types:
Note: int data type is 2 byte signed on some compilers and 4 on other.
Type name Size Range
char 1 byte signed -128 to 127
unsigned char 1 byte unsigned 0 to 255
short 2 byte signed -32,768 to 32,767
unsigned short 2 byte unsigned 0 to 65,535
long 4 byte signed -2,147,483,648 to 2,147,483,647
unsigned long 4 byte unsigned 0 to 4,294,967,295
long long 8 byte signed
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
unsigned long long 8 byte unsigned 0 to 18,446,744,073,709,551,615
Variables & Data types
• char type is also used to represent alphabets.
• Floating point data types (Real values):
• Boolean data type (true or false state variable): bool its size is 1 byte.
Type name Size Range Precision
float 4 bytes ±1.18 x 10-38 to ±3.4 x 1038 6-9 significant digits, typically 7
double 8 bytes ±2.23 x 10-308 to ±1.80 x 10308 15-18 significant digits, typically 16
Operators
• Arithmetic
Operator Symbol Form Operation
Assignment = x = y Assign value y to x
Addition + x + y x plus y
Subtraction - x - y x minus y
Multiplication * x * y x multiplied by y
Division / x / y x divided by y
Addition assignment =+ x += y Add y to x
Subtraction assignment -= x -= y Subtract y from x
Multiplication assignment =* x *= y Multiply x by y
Division assignment =/ x /= y Divide x by y
Modulus assignment =% x %= y Put the remainder of x / y in x
Operators
• Arithmetic
• For the complete list of operators precedence go to:
http://www.learncpp.com/cpp-tutorial/31-precedence-and-
associativity/
Operator Symbol Form Operation
Prefix increment (pre-increment) ++ ++x Increment x, then evaluate x
Prefix decrement (pre-decrement) –– ––x Decrement x, then evaluate x
Postfix increment (post-increment) ++ x++ Evaluate x, then increment x
Postfix decrement (post-decrement) –– x–– Evaluate x, then decrement x
Prefix increment (pre-increment) ++ ++x Increment x, then evaluate x
Operators
• Relational operators (comparisons)
Operator Symbol Form Operation
Greater than > x > y true if x is greater than y, false otherwise
Less than < x < y true if x is less than y, false otherwise
Greater than or equals >= x >= y true if x is greater than or equal to y, false otherwise
Less than or equals <= x <= y true if x is less than or equal to y, false otherwise
Equality == x == y true if x equals y, false otherwise
Inequality =! x != y true if x does not equal y, false otherwise
Operator Symbol Form Operation
Greater than > x > y true if x is greater than y, false otherwise
Less than < x < y true if x is less than y, false otherwise
Greater than or equals >= x >= y true if x is greater than or equal to y, false otherwise
Operators
• Logical operators
• And there are a lot of other operators we will discuss them when
we will approach them.
Operator Symbol Form Operation
Logical NOT ! !x true if x is false, or false if x is true
Logical AND && x && y true if both x and y are true, false otherwise
Logical OR || x || y true if either x or y are true, false otherwise
Flow control statements
• If statement.
• Switch statement.
• While loop statement.
• For loop statement.
• Break and continue.
Flow control: if statement
• Syntax: If (Conditional expression)
one expression or {expressions block}
else if (Conditional expression)
one expression or {expressions block}
else if (Conditional expression)
one expression or {expressions block}
.
.
.
else if (Conditional expression)
one expression or {expressions block}
else
one expression or {expressions block}
Flow control: switch statement
• Syntax: switch(integer expression)
{
case (case value):
[break];
case (case value):
[break];
case (case value):
[break];
default:
[break];
}
Flow control: switch statement
• Used over if statement if we have a lot of equal condition if
statement (it is much faster than if statement).
• Note: we can leave out the brake statement if we want some cases
to do the same statements.
Flow control: while loop statement
• Syntax: while (Conditional expression)
one expression or {expressions block}
• Anther form: do
one expression or {expressions block}
while (Conditional expression)
• Used when we don’t know how many times we will loop.
• Note: we can use it to do infant loop if the condition will never be
false (ex. 10>0 , true).
Flow control: for loop statement
• Syntax
for(loop initialization; loop condition; increment expression)
one expression or {expressions block}
• Used when we know exactly how many times we will loop.
• We can omit the loop initialization , loop condition or increment
expression if we want to.
• Note: we can use it to do infant loop if the loop condition will never
be false (ex. 10>0 , true) or if we leave out the loop condition .
Flow control: break & continue
• If we want to skip the running iteration of the loop, we can use the
continue statement.
• If we want to terminate all the work of the loop, we can use the
break statement.
IO methods
• In C++ if we want to output something on the screen, we can use
cout stream.
• If we want to get an input from what the user is typing on the
screen, we can use cin stream.
• In general, cin cout streams are slow in programing contests.
• To get faster IO methods you may use the C programing language
methods printf and scanf.
• Or you may put this statement before any cin or cout statement:
ios::sync_with_stdio (false);
• This statement turns off the synchronization between the C++ IO
and C IO, so once you use it you can’t use printf and scanf.
Example 2: A. Choosing Teams
The Saratov State University Olympiad Programmers Training Center (SSU
OPTC) has n students. For each student you know the number of times
he/she has participated in the ACM ICPC world programming
championship. According to the ACM ICPC rules, each person can
participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in
the world championship. Each team must consist of exactly three
people, at that, any person cannot be a member of two or more teams.
What maximum number of teams can the head make if he wants each
team to participate in the world championship with the same members
at least k times?
Solve at:
Example 2: A. Choosing Teams
Input:
The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The
next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the
number of times the i-th person participated in the ACM ICPC world
championship.
Output:
Print a single number — the answer to the problem.
Solve at:
Example 2: A. Choosing Teams
1. #include <iostream>
2. using namespace std;
3. int main() {
4. ios::sync_with_stdio(false);
5. int teamscount = 0, invidualcount = 0, n, k, x;
6. cin >> n >> k;
7. for (int i = 0; i < n; i++) {
8. cin >> x;
9. if (k + x <= 5) {
10. invidualcount++;
11. if (invidualcount == 3) {
12. invidualcount = 0;
13. teamscount++;
14. }
15. }
16. }
17. cout << teamscount << endl;
18. return 0;
19.}
Solve at:
Example 3: The 3n + 1 problem
Background
Problems in Computer Science are often classified as belonging to a certain
class of problems (e.g., NP, Unsolvable, Recursive). In this problem you will be
analyzing a property of an algorithm whose classification is not known for all
possible inputs.
The Problem
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then tex2html_wrap_inline44
5. else tex2html_wrap_inline46
6. GOTO 2
Solve at:
Example 3: The 3n + 1 problem
Given the input 22, the following sequence of numbers will be printed 22 11 34
17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed)
for any integral input value. Despite the simplicity of the algorithm, it is
unknown whether this conjecture is true. It has been verified, however, for all
integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers
than this.)
Given an input n, it is possible to determine the number of numbers printed
(including the 1). For a given n this is called the cycle-length of n. In the
example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length
over all numbers between i and j.
Solve at:
Example 3: The 3n + 1 problem
The Input
The input will consist of a series of pairs of integers i and j, one pair of integers
per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the
maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output
For each pair of input integers i and j you should output i, j, and the maximum
cycle length for integers between and including i and j. These three numbers
should be separated by at least one space with all three numbers on one line
and with one line of output for each line of input. The integers i and j must
appear in the output in the same order in which they appeared in the input
and should be followed by the maximum cycle length (on the same line).
Solve at:
Example 3: The 3n + 1 problem
1. #include <iostream>
2. using namespace std;
3. int main() {
4. ios::sync_with_stdio(false);
5. int n, m;
6. while (cin >> n >> m) {
7. int maxCycle = 0;
8. int start,end;
9. if (n > m) {
10. start = m;
11. end = n;
12. }
13. else {
14. start = n;
15. end = m;
16. }
Solve at:
17. for(int i = start;i <= end; i++){
18. int Cycle = 1, x = i;
19. while (x > 1){
20. if (x % 2)
21. x = x * 3 + 1;
22. else
23. x = x / 2;
24. Cycle++;
25. }
26. if (Cycle > maxCycle)
27. maxCycle = Cycle;
28. }
29. cout<<n<<" "<<m<<" "<<maxCycle<<endl;
30. }
31. return 0;
32.}
Example 4: B. Present from Lena
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a
present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The
largest digit n should be located in the centre. The digits should decrease as they approach
the edges. For example, for n = 5 the handkerchief pattern should look like that:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 3 4 3 2 1 0
0 1 2 3 4 5 4 3 2 1 0
0 1 2 3 4 3 2 1 0
0 1 2 3 2 1 0
0 1 2 1 0
0 1 0
0
Solve at:
Example 4: B. Present from Lena
Your task is to determine the way the handkerchief will look like by the
given n.
Input
The first line contains the single integer n (2 ≤ n ≤ 9).
Output
Print a picture for the given n. You should strictly observe the number of
spaces before the first digit on each line. Every two adjacent digits in the
same line should be separated by exactly one space. There should be no
spaces after the last digit at the end of each line.
Solve at:
Other Exercises
Try these good exercises and remember the more you exercise, the
better you will become ;).
• Codeforces A. Nearly Lucky Number
• Codeforces A. I_love_%username%
• Codeforces A. Lunch Rush
• UVA 00278 – Chess
• UVA 10976 - Fractions Again?!
Thank you :) :) :)

Contenu connexe

Tendances

String & its application
String & its applicationString & its application
String & its application
Tech_MX
 

Tendances (19)

C++ theory
C++ theoryC++ theory
C++ theory
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
String & its application
String & its applicationString & its application
String & its application
 
06.Loops
06.Loops06.Loops
06.Loops
 
14 strings
14 strings14 strings
14 strings
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Python ppt
Python pptPython ppt
Python ppt
 
Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02
 
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVSCBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
CBSE XII COMPUTER SCIENCE STUDY MATERIAL BY KVS
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
C string
C stringC string
C string
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
 
C# Strings
C# StringsC# Strings
C# Strings
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
Modern C++
Modern C++Modern C++
Modern C++
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 

Similaire à Acm aleppo cpc training introduction 1

presentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptxpresentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptx
GAURAVRATHORE86
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
RujanTimsina1
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Alpana Gupta
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
 

Similaire à Acm aleppo cpc training introduction 1 (20)

presentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptxpresentation_python_11_1569171345_375360.pptx
presentation_python_11_1569171345_375360.pptx
 
Lec-1c.pdf
Lec-1c.pdfLec-1c.pdf
Lec-1c.pdf
 
0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
Lecture1
Lecture1Lecture1
Lecture1
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1Begin with c++ Fekra Course #1
Begin with c++ Fekra Course #1
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
Foundations of Programming Part I
Foundations of Programming Part IFoundations of Programming Part I
Foundations of Programming Part I
 
Lesson 5 .1 selection structure
Lesson 5 .1 selection structureLesson 5 .1 selection structure
Lesson 5 .1 selection structure
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Acm aleppo cpc training introduction 1

  • 1. ACM Aleppo CPC Training Part 1 C++ Programming Concepts By Ahmad Bashar Eter
  • 2. About the contest and the training • What is the ACM ICPC? • Who this contest is for? • What will I get from this contest?
  • 3. About the contest and the training • What should I do to win in this contest? • Who this training is for? • How far I will reach in programming contest word after this part is finished?
  • 4. The Problems Each problem has: • Problem description • Input description • Output description • Sample input (1 or more) • Sample output (1 or more)
  • 5. Judge Response • Accepted • Wrong Answer • Time Limit Exceeded • Runtime Error • Compilation Error • Presentation Error
  • 6. Example 1 HQ9+ is a joke programming language which has only four one-character instructions: "H" prints "Hello, World!", "Q" prints the source code of the program itself, "9" prints the lyrics of "99 Bottles of Beer" song, "+" increments the value stored in the internal accumulator. Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored. You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output. Input The input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive. Output Output "YES", if executing the program will produce any output, and "NO" otherwise. Solve at: http://codeforces.com/problemset/problem/133/A
  • 7. Self Training resources • First of all Google and Wikipedia. • To ask a question go to www.stackoverflow.com • C++ and STL libraries reference: www.cplusplus.com • C++ tutorials: www.learncpp.com • Online Judges: Code Forces UVA A2OJ Top Coder SPOJ Hacker Earth
  • 8. Self Training resources Books: 1. Programming Challenges 2. Competitive Programming 3 Tutorials: Topcoder tutorials: Hacker Earth Code Monk GeeksForGeeks.org
  • 10. Variables & Data types • To define a variable: [TypeName] [VariableName]; • Integer data types: Note: int data type is 2 byte signed on some compilers and 4 on other. Type name Size Range char 1 byte signed -128 to 127 unsigned char 1 byte unsigned 0 to 255 short 2 byte signed -32,768 to 32,767 unsigned short 2 byte unsigned 0 to 65,535 long 4 byte signed -2,147,483,648 to 2,147,483,647 unsigned long 4 byte unsigned 0 to 4,294,967,295 long long 8 byte signed -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 unsigned long long 8 byte unsigned 0 to 18,446,744,073,709,551,615
  • 11. Variables & Data types • char type is also used to represent alphabets. • Floating point data types (Real values): • Boolean data type (true or false state variable): bool its size is 1 byte. Type name Size Range Precision float 4 bytes ±1.18 x 10-38 to ±3.4 x 1038 6-9 significant digits, typically 7 double 8 bytes ±2.23 x 10-308 to ±1.80 x 10308 15-18 significant digits, typically 16
  • 12. Operators • Arithmetic Operator Symbol Form Operation Assignment = x = y Assign value y to x Addition + x + y x plus y Subtraction - x - y x minus y Multiplication * x * y x multiplied by y Division / x / y x divided by y Addition assignment =+ x += y Add y to x Subtraction assignment -= x -= y Subtract y from x Multiplication assignment =* x *= y Multiply x by y Division assignment =/ x /= y Divide x by y Modulus assignment =% x %= y Put the remainder of x / y in x
  • 13. Operators • Arithmetic • For the complete list of operators precedence go to: http://www.learncpp.com/cpp-tutorial/31-precedence-and- associativity/ Operator Symbol Form Operation Prefix increment (pre-increment) ++ ++x Increment x, then evaluate x Prefix decrement (pre-decrement) –– ––x Decrement x, then evaluate x Postfix increment (post-increment) ++ x++ Evaluate x, then increment x Postfix decrement (post-decrement) –– x–– Evaluate x, then decrement x Prefix increment (pre-increment) ++ ++x Increment x, then evaluate x
  • 14. Operators • Relational operators (comparisons) Operator Symbol Form Operation Greater than > x > y true if x is greater than y, false otherwise Less than < x < y true if x is less than y, false otherwise Greater than or equals >= x >= y true if x is greater than or equal to y, false otherwise Less than or equals <= x <= y true if x is less than or equal to y, false otherwise Equality == x == y true if x equals y, false otherwise Inequality =! x != y true if x does not equal y, false otherwise Operator Symbol Form Operation Greater than > x > y true if x is greater than y, false otherwise Less than < x < y true if x is less than y, false otherwise Greater than or equals >= x >= y true if x is greater than or equal to y, false otherwise
  • 15. Operators • Logical operators • And there are a lot of other operators we will discuss them when we will approach them. Operator Symbol Form Operation Logical NOT ! !x true if x is false, or false if x is true Logical AND && x && y true if both x and y are true, false otherwise Logical OR || x || y true if either x or y are true, false otherwise
  • 16. Flow control statements • If statement. • Switch statement. • While loop statement. • For loop statement. • Break and continue.
  • 17. Flow control: if statement • Syntax: If (Conditional expression) one expression or {expressions block} else if (Conditional expression) one expression or {expressions block} else if (Conditional expression) one expression or {expressions block} . . . else if (Conditional expression) one expression or {expressions block} else one expression or {expressions block}
  • 18. Flow control: switch statement • Syntax: switch(integer expression) { case (case value): [break]; case (case value): [break]; case (case value): [break]; default: [break]; }
  • 19. Flow control: switch statement • Used over if statement if we have a lot of equal condition if statement (it is much faster than if statement). • Note: we can leave out the brake statement if we want some cases to do the same statements.
  • 20. Flow control: while loop statement • Syntax: while (Conditional expression) one expression or {expressions block} • Anther form: do one expression or {expressions block} while (Conditional expression) • Used when we don’t know how many times we will loop. • Note: we can use it to do infant loop if the condition will never be false (ex. 10>0 , true).
  • 21. Flow control: for loop statement • Syntax for(loop initialization; loop condition; increment expression) one expression or {expressions block} • Used when we know exactly how many times we will loop. • We can omit the loop initialization , loop condition or increment expression if we want to. • Note: we can use it to do infant loop if the loop condition will never be false (ex. 10>0 , true) or if we leave out the loop condition .
  • 22. Flow control: break & continue • If we want to skip the running iteration of the loop, we can use the continue statement. • If we want to terminate all the work of the loop, we can use the break statement.
  • 23. IO methods • In C++ if we want to output something on the screen, we can use cout stream. • If we want to get an input from what the user is typing on the screen, we can use cin stream. • In general, cin cout streams are slow in programing contests. • To get faster IO methods you may use the C programing language methods printf and scanf. • Or you may put this statement before any cin or cout statement: ios::sync_with_stdio (false); • This statement turns off the synchronization between the C++ IO and C IO, so once you use it you can’t use printf and scanf.
  • 24. Example 2: A. Choosing Teams The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times? Solve at:
  • 25. Example 2: A. Choosing Teams Input: The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship. Output: Print a single number — the answer to the problem. Solve at:
  • 26. Example 2: A. Choosing Teams 1. #include <iostream> 2. using namespace std; 3. int main() { 4. ios::sync_with_stdio(false); 5. int teamscount = 0, invidualcount = 0, n, k, x; 6. cin >> n >> k; 7. for (int i = 0; i < n; i++) { 8. cin >> x; 9. if (k + x <= 5) { 10. invidualcount++; 11. if (invidualcount == 3) { 12. invidualcount = 0; 13. teamscount++; 14. } 15. } 16. } 17. cout << teamscount << endl; 18. return 0; 19.} Solve at:
  • 27. Example 3: The 3n + 1 problem Background Problems in Computer Science are often classified as belonging to a certain class of problems (e.g., NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs. The Problem Consider the following algorithm: 1. input n 2. print n 3. if n = 1 then STOP 4. if n is odd then tex2html_wrap_inline44 5. else tex2html_wrap_inline46 6. GOTO 2 Solve at:
  • 28. Example 3: The 3n + 1 problem Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.) Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16. For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j. Solve at:
  • 29. Example 3: The 3n + 1 problem The Input The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0. You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j. You can assume that no operation overflows a 32-bit integer. The Output For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line). Solve at:
  • 30. Example 3: The 3n + 1 problem 1. #include <iostream> 2. using namespace std; 3. int main() { 4. ios::sync_with_stdio(false); 5. int n, m; 6. while (cin >> n >> m) { 7. int maxCycle = 0; 8. int start,end; 9. if (n > m) { 10. start = m; 11. end = n; 12. } 13. else { 14. start = n; 15. end = m; 16. } Solve at: 17. for(int i = start;i <= end; i++){ 18. int Cycle = 1, x = i; 19. while (x > 1){ 20. if (x % 2) 21. x = x * 3 + 1; 22. else 23. x = x / 2; 24. Cycle++; 25. } 26. if (Cycle > maxCycle) 27. maxCycle = Cycle; 28. } 29. cout<<n<<" "<<m<<" "<<maxCycle<<endl; 30. } 31. return 0; 32.}
  • 31. Example 4: B. Present from Lena Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that: 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 4 5 4 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Solve at:
  • 32. Example 4: B. Present from Lena Your task is to determine the way the handkerchief will look like by the given n. Input The first line contains the single integer n (2 ≤ n ≤ 9). Output Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line. Solve at:
  • 33. Other Exercises Try these good exercises and remember the more you exercise, the better you will become ;). • Codeforces A. Nearly Lucky Number • Codeforces A. I_love_%username% • Codeforces A. Lunch Rush • UVA 00278 – Chess • UVA 10976 - Fractions Again?!
  • 34. Thank you :) :) :)