SlideShare a Scribd company logo
ACM Aleppo CPC Training
Part 1 C++ Programming Concepts
By Ahmad Bashar Eter
Math problems
• We’ve seen a lot of math problems till now.
• Remember to be precise when you use the floating point numbers
or constants.
• C++ cmath (or math.h) reference can be found hear:
http://www.cplusplus.com/reference/cmath/
• Some problems need the output to be formatted in special way
• You can set the number of decimals places after the point for float
numbers by setprecision(4) after including iomanip library.
• There are a lot of IO manipulation technique in c++ the flowing
table show a lot of flags to manipulate the IO streams.
Math problems
field member constant effect when set
independent
flags
ios::boolalpha read/write bool elements as alphabetic strings (true and false).
ios::showbase write integral values preceded by their corresponding numeric base prefix.
ios::showpoint write floating-point values including always the decimal point.
ios::showpos write non-negative numerical values preceded by a plus sign (+).
ios::skipws skip leading whitespaces on certain input operations.
ios::unitbuf flush output after each inserting operation.
ios::uppercase write uppercase letters replacing lowercase letters in certain insertion operations.
numerical base
(basefield)
ios::dec read/write integral values using decimal base format.
ios::hex read/write integral values using hexadecimal base format.
ios::oct read/write integral values using octal base format.
float format
(floatfield)
ios::fixed write floating point values in fixed-point notation.
ios::scientific write floating-point values in scientific notation.
adjustment
(adjustfield)
ios::internal
the output is padded to the field width by inserting fill characters at a specified
internal point.
ios::left the output is padded to the field width appending fill characters at the end.
ios::right the output is padded to the field width by inserting fill characters at the beginning.
Math problems
• For the full IO manipulation techniques see these pages and
remember to ask Google about it:
• http://www.cplusplus.com/reference/ios/ios_base/fmtflags/
• http://www.cplusplus.com/reference/iomanip/
Time Complexity Analysis:
• Time Complexity is a way to estimate the time that the algorithm
will take to do its job relative to the input size.
• consider we have an algorithm that iterate over all n element of the
input one time we can say that this algorithm complexity Is relative
to n.
• consider we have an algorithm that iterate over all n element and
for each element we iterate another n times (like if we have 2 for
loop nested inside each other) we can say that this algorithm
complexity Is relative to 𝒏 𝟐.
• There is a lot of notation to use when we want to estimate Time
Complexity, we are interested in the Big O notation.
Time Complexity Analysis:
• Big O notation used to estimate the upper bound of the growth rate
of a function and defined as:
• Consider we have two function 𝒇 𝒙 , 𝒈(𝒙) defined on some subset
of real numbers.
• We say that: 𝒇 𝒙 = 𝑶 𝒈 𝒙
if and only if there is positive constant C
and a number 𝒙 𝟎 such that
the flowing is true:
𝒇 𝒙 ≤ 𝑪 𝒈 𝒙 𝒇𝒐𝒓 𝒂𝒍𝒍 𝒙 > 𝒙 𝟎
Reference:
Time Complexity Analysis:
• Away from mathematics in real life when we want to compute the
complexity of an algorithm we see what is the maximum number of
operations that an algorithm may do by counting the number of
nested loops or by understanding the functions behavior.
• And in Big O notation we eliminate the low order terms (ex. If we
have an algorithm that do 𝟕𝒏 𝟑 + 𝟔𝒏 𝟐 𝒍𝒐𝒈 𝒏 + 𝒏 opration we say
this algorithm is order of n cube or 𝑶(𝒏 𝟑) ).
• So se consider the highest order (or the highest growth) term only
without the multiplied constants.
• From now we will calculate the complexity of every problem we will
solve.
Reference:
Time Complexity in CP:
• In competitive programing word we have to analyze the time
complexity of a problem in order to avoid the TLE response.
• Typically if your algorithm will do 𝟓𝟎 × 𝟏𝟎 𝟔
operation for each
second then it is ok.
• The following table contain the most common worst case Time
complexity with the maximum recommended input size:
Reference:
Time Complexity in CP:
CommentComplexityN
e.g. Enumerating permutations𝑶 𝒏! , 𝑶(𝒏 𝟔
)≤ [10…11]
e.g. DP TSP𝑶(𝟐 𝒏
× 𝒏 𝟐
)≤ [15…18]
e.g. DP with bitmask technique, Perfect matching𝑶(𝟐 𝒏 × 𝒏)≤ [18…22]
e.g. DP with 3 dimensions + O(n) loop𝑶(𝒏 𝟒)≤ 100
e.g. Floyd Warshall’s𝑶(𝒏 𝟑
)≤ 400
e.g. 2-nested loops + (a tree-related DS or binary
search)
𝑶(𝒏 𝟐
𝒍𝒐𝒈 𝟐 𝒏)≤ 𝟐 × 𝟏𝟎 𝟑
e.g. Bubble/Selection/Insertion Sort𝑶(𝒏 𝟐
)≤ 𝟏𝟎 𝟒
e.g. Merge Sort, building Segment Tree𝑶(𝒏 𝒍𝒐𝒈 𝟐 𝒏)≤ 𝟏𝟎 𝟔
Most contest problem has n ≤ 1M (I/O bottleneck)𝑶 𝒏 , 𝑶 𝒍𝒐𝒈 𝟐 𝒏 , 𝑶(𝟏)≤ 𝟏𝟎 𝟖
Reference:
Example 1: UVA - 441 - Lotto
In the German Lotto you have to select 6 numbers from the set {1,2,...,49}.
A popular strategy to play Lotto - although it doesn’t increase your chance of
winning — is to select a subset S containing k (k > 6) of these 49 numbers,
and then play several games with choosing numbers only from S.
For example, for k = 8 and S = {1, 2, 3, 5, 8, 13, 21, 34} there are 28 possible
games: [1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], ...,
[3,5,8,13,21,34].
Your job is to write a program that reads in the number k and the set S and then
prints all possible games choosing numbers only from S.
Solve At:
Example 1: UVA - 441 - Lotto
Input The input file will contain one or more test cases. Each test case consists of
one line containing several integers separated from each other by spaces. The
first integer on the line will be the number k (6 < k < 13). Then k integers,
specifying the set S, will follow in ascending order. Input will be terminated by a
value of zero (0) for k.
Output For each test case, print all possible games, each game on one line. The
numbers of each game have to be sorted in ascending order and separated from
each other by exactly one space. The games themselves have to be sorted
lexicographically, that means sorted by the lowest number first, then by the
second lowest and so on, as demonstrated in the sample output below. The test
cases have to be separated from each other by exactly one blank line. Do not put
a blank line after the last test case.
Solve At:
Example 1: UVA - 441 - Lotto
Sample Input
7 1 2 3 4 5 6 7
0
Solve At:
Sample Output
1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 6 7
1 2 3 5 6 7
1 2 4 5 6 7
1 3 4 5 6 7
2 3 4 5 6 7
Example 2: UVA - 10360 - Rat Attack
Baaaam! Another deadly gas bomb explodes in Manhattan’s underworld.
Rats have taken over the sewerage and the city council is doing everything to get
the rat population under control.
As you know, Manhattan is organized in a regular fashion with streets and
avenues arranged like a rectangular grid.
Waste water drains run beneath the streets in the same arrangement and the
rats have always set up their nests below street intersections.
The only viable method to extinguish them is to use gas bombs like the one
which has just exploded.
Solve At:
Example 2: UVA - 10360 - Rat Attack
However, gas bombs are not only dangerous for rats. The skyscrapers above the
explosion point have to be evacuated in advance and so the point of rat attack
must be chosen very carefully.
The gas bombs used are built by a company called American Catastrophe
Management (ACM) and they are sold under the heading of “smart rat gas”.
They are smart because —when fired— the gas spreads in a rectangular fashion
through the under street canals.
The strength of a gas bomb is given by a number d which specifies the
rectangular “radius” of the gas diffusion area.
Solve At:
Example 2: UVA - 10360 - Rat Attack
For example, the figure shows what happens when a bomb with d = 1 explodes.
Solve At:
Example 2: UVA - 10360 - Rat Attack
The area of interest consists of a discrete grid of 1025 × 1025 fields.
Rat exterminator scouts have given a detailed report on where rat populations of
different sizes have built their nests. You are given a gas bomb with strength d and
your task is to find an explosion location for this gas bomb which extinguishes the
largest number of rats. The best position is determined by the following criteria:
1) The sum of all rat population sizes within the diffusion area of the gas bomb
(given by d) is maximal.
2) If there is more than one of these best positions then the location with the
“minimal” position will be chosen. Positions are ordered first by their x coordinate
and second by their y coordinate. Formally, given a location (x1, y1) on the grid, a
point (x2, y2) is within the diffusion area of a gas bomb with strength d if the
following equation holds: max(abs(x2 − x1), abs(y2 − y1)) ≤ d
Solve At:
Example 2: UVA - 10360 - Rat Attack
Input The first line contains the number of scenarios in the input.
For each scenario the first line contains the strength d of the gas bomb in the
scenario (1 ≤ d ≤ 50). The second line contains the number n (1 ≤ n ≤ 20000) of rat
populations. Then for every rat population follows a line containing three
integers separated by spaces for the position (x, y) and “size” i of the population
(1 ≤ i ≤ 255).
It is guaranteed that position coordinates are valid (i.e., in the range between 0
and 1024) and no position is given more than once.
Output For every problem print a line containing the x and y coordinate of the
chosen location for the gas bomb, followed by the sum of the rat population sizes
which will be extinguished. The three numbers must be separated by a space.
Solve At:
Example 2: UVA - 10360 - Rat Attack
Sample Input
1
1
2
4 4 10
6 6 20
Solve At:
Sample Output
5 5 30
Bit manipulation
• In competitive programing many problems need to utilize numbers
as there bit representation.
• The techniques of utilize the numbers bit representation is called Bit
manipulation.
• We will see in this part how to:
1. set or unset bit in number and check the state of a bit.
2. Know the right most bit.
3. Check if a number is power of 2.
4. Count the number of ones in binary representation.
5. Check if a number is odd or even or divide by 2.
Reference:
Bit manipulation
• To set the i-th position bit in a number we can do an OR operator
with a number that have a single 1 at the i-th position like that:
num = num | (1 << i);
• To unset the i-th bit in a number we must clear the i-th bit and leave
all numbers as it by this:
num = num & ~(1 << i);
• To check the state of the i-th bit we can do AND operator on the
number and the i-th bit like this:
if(num & (1<<i))
• To filp the state of a bits in number we can use the XOR operator:
num ^ mask; // if num=101 and mask= 011 the result
// will be flipped at each 1 in the
// mask and will be 110
Reference:
Bit manipulation
• We can use the last 3 techniques to represent a subset of element of
a set by a number which the 0 or 1 in it means that we take or leave
the elements.
• E.g. the flowing set {1,3,9,7,5,4} and the subset {9,5,4} can be
represented as the binary number 001011.
• This number is called bit mask.
Reference:
Bit manipulation
• To clear the right most digit in a number we can do & on the
number and the number-1:
x = num & num-1;
• Check if the number is power of 2 we can clear the right most digit if
the number became 0 then it is power of 2 (power of 2 contain
single 1 in binary representation) and the only power of 2 that don’t
have ones in it is 0 then we can do like that:
if(x && !(x&x-1))
• To divide a number by 2 we can simply shift it to the right by 1 and
to multiply it by 2 we can shift it to the left.
• In general to divide by any x that power of 2 we can shift to the right
by the log2 of x, and to multiply by any x that is power of 2 we can
shift to the left by log2 of x.
Reference:
Bit manipulation
• To determine if a number is odd or even we can simply check the
first bit if it set:
if(x & 1) cout <<”odd”; else cout<<“even”;
• To count the number of ones effectively we can loop while the
number is not 0 and clear the right most 1:
while( x ) {
x = x&(x-1);
count++;
}
• To get the right most digit we can simply XOR the number with it
after removing the right most digit:
x ^ ( x & (x-1))
Reference:
Example 3: Monk's Choice of Numbers
Monk loves cakes! He visits the Binary Bakery to buy some of his favorite
cheesecakes.
The owner of the bakery, Bob, is a clever man. He does not want Monk to finish
all his cheesecakes. Hence, he plays a game.
The Monk is given N numbers and has to select K of these numbers. For each
number that Monk chooses, he will get as many cheesecakes as the number
of 1's in the Binary representation of the number i.e. the number of bits that are
set.
Help Monk find the maximum number of cakes that he can have.
Solve At:
Example 3: Monk's Choice of Numbers
Input:
The first line of input contains T. T test cases follow.
First line of each test cases contains 2 space-separated integers N and K.
The next line contains N space-separated integers.
Output:
For each test cases, print the answer in a new line.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 103
0 ≤ K ≤ N
0 ≤ Numbers ≤ 105
Solve At:
Example 3: Monk's Choice of Numbers
Sample Input
1
4 2
6 1 2 0
Solve At:
Sample Output
3
Example 4: Monk and his Friend
Monk has a very good friend, Puchi. As weird as his name, are the games he
plays.
One fine day, they decided to play a game to test how diverse their choices are.
Both of them choose exactly one integer each. Monk chooses an integer M and
Puchi chooses an integer P.
The diversity of their choices is defined as the number of bits whose status is
different in the binary representation of M and P , i.e. , count of bits that are
,either set in M and unset in P or set in P and unset in M.
Find the answer to their game.
Solve At:
Example 4: Monk and his Friend
Input:
First line contains T. T test cases follow.
Each test case consists of 2 space-separated integers P and M.
Output:
Print the answer to each test case in a new line.
Constraints:
1 ≤ T ≤ 104
0 ≤ M, P ≤ 1016
Solve At:
Example 4: Monk and his Friend
Sample Input
4
1 4
3 3
5 1
8 7
Solve At:
Sample Output
2
0
1
4
Thank you :) :) :)

More Related Content

What's hot

45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
jatin batra
 
Ch8 Arrays
Ch8 ArraysCh8 Arrays
Ch8 Arrays
SzeChingChen
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
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
Ali Aminian
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Rakesh Roshan
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
Md. Ashikur Rahman
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
shashikant pabari
 
The Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 MigrationThe Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 Migration
Joel Falcou
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogramprincepavan
 

What's hot (20)

45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
Ch8 Arrays
Ch8 ArraysCh8 Arrays
Ch8 Arrays
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
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++ theory
C++ theoryC++ theory
C++ theory
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
14 strings
14 strings14 strings
14 strings
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
 
String & its application
String & its applicationString & its application
String & its application
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
The Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 MigrationThe Goal and The Journey - Turning back on one year of C++14 Migration
The Goal and The Journey - Turning back on one year of C++14 Migration
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Python ppt
Python pptPython ppt
Python ppt
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 

Similar to Acm aleppo cpc training fifth session

A01
A01A01
A01
lksoo
 
Design and analysis of algorithms
Design and analysis of algorithmsDesign and analysis of algorithms
Design and analysis of algorithms
PSG College of Technology
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
yashodamb
 
4tocontest
4tocontest4tocontest
4tocontestberthin
 
Introduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdfIntroduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdf
TulasiramKandula1
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
skilljiolms
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
TANVIRAHMED611926
 
CP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithmsCP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithms
Sheba41
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdf
pasinduneshan
 
DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptx
NishaS88
 
13 Amortized Analysis
13 Amortized Analysis13 Amortized Analysis
13 Amortized Analysis
Andres Mendez-Vazquez
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
Gradeup
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
James Wong
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
Harry Potter
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
Luis Goldster
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
Fraboni Ec
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
Young Alista
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
Tony Nguyen
 

Similar to Acm aleppo cpc training fifth session (20)

A01
A01A01
A01
 
Design and analysis of algorithms
Design and analysis of algorithmsDesign and analysis of algorithms
Design and analysis of algorithms
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
4tocontest
4tocontest4tocontest
4tocontest
 
Es272 ch1
Es272 ch1Es272 ch1
Es272 ch1
 
Introduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdfIntroduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdf
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
CP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithmsCP4151 Advanced data structures and algorithms
CP4151 Advanced data structures and algorithms
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdf
 
DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptx
 
13 Amortized Analysis
13 Amortized Analysis13 Amortized Analysis
13 Amortized Analysis
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacksqueueslists
StacksqueueslistsStacksqueueslists
Stacksqueueslists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 

Recently uploaded

2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 

Acm aleppo cpc training fifth session

  • 1. ACM Aleppo CPC Training Part 1 C++ Programming Concepts By Ahmad Bashar Eter
  • 2. Math problems • We’ve seen a lot of math problems till now. • Remember to be precise when you use the floating point numbers or constants. • C++ cmath (or math.h) reference can be found hear: http://www.cplusplus.com/reference/cmath/ • Some problems need the output to be formatted in special way • You can set the number of decimals places after the point for float numbers by setprecision(4) after including iomanip library. • There are a lot of IO manipulation technique in c++ the flowing table show a lot of flags to manipulate the IO streams.
  • 3. Math problems field member constant effect when set independent flags ios::boolalpha read/write bool elements as alphabetic strings (true and false). ios::showbase write integral values preceded by their corresponding numeric base prefix. ios::showpoint write floating-point values including always the decimal point. ios::showpos write non-negative numerical values preceded by a plus sign (+). ios::skipws skip leading whitespaces on certain input operations. ios::unitbuf flush output after each inserting operation. ios::uppercase write uppercase letters replacing lowercase letters in certain insertion operations. numerical base (basefield) ios::dec read/write integral values using decimal base format. ios::hex read/write integral values using hexadecimal base format. ios::oct read/write integral values using octal base format. float format (floatfield) ios::fixed write floating point values in fixed-point notation. ios::scientific write floating-point values in scientific notation. adjustment (adjustfield) ios::internal the output is padded to the field width by inserting fill characters at a specified internal point. ios::left the output is padded to the field width appending fill characters at the end. ios::right the output is padded to the field width by inserting fill characters at the beginning.
  • 4. Math problems • For the full IO manipulation techniques see these pages and remember to ask Google about it: • http://www.cplusplus.com/reference/ios/ios_base/fmtflags/ • http://www.cplusplus.com/reference/iomanip/
  • 5. Time Complexity Analysis: • Time Complexity is a way to estimate the time that the algorithm will take to do its job relative to the input size. • consider we have an algorithm that iterate over all n element of the input one time we can say that this algorithm complexity Is relative to n. • consider we have an algorithm that iterate over all n element and for each element we iterate another n times (like if we have 2 for loop nested inside each other) we can say that this algorithm complexity Is relative to 𝒏 𝟐. • There is a lot of notation to use when we want to estimate Time Complexity, we are interested in the Big O notation.
  • 6. Time Complexity Analysis: • Big O notation used to estimate the upper bound of the growth rate of a function and defined as: • Consider we have two function 𝒇 𝒙 , 𝒈(𝒙) defined on some subset of real numbers. • We say that: 𝒇 𝒙 = 𝑶 𝒈 𝒙 if and only if there is positive constant C and a number 𝒙 𝟎 such that the flowing is true: 𝒇 𝒙 ≤ 𝑪 𝒈 𝒙 𝒇𝒐𝒓 𝒂𝒍𝒍 𝒙 > 𝒙 𝟎 Reference:
  • 7. Time Complexity Analysis: • Away from mathematics in real life when we want to compute the complexity of an algorithm we see what is the maximum number of operations that an algorithm may do by counting the number of nested loops or by understanding the functions behavior. • And in Big O notation we eliminate the low order terms (ex. If we have an algorithm that do 𝟕𝒏 𝟑 + 𝟔𝒏 𝟐 𝒍𝒐𝒈 𝒏 + 𝒏 opration we say this algorithm is order of n cube or 𝑶(𝒏 𝟑) ). • So se consider the highest order (or the highest growth) term only without the multiplied constants. • From now we will calculate the complexity of every problem we will solve. Reference:
  • 8. Time Complexity in CP: • In competitive programing word we have to analyze the time complexity of a problem in order to avoid the TLE response. • Typically if your algorithm will do 𝟓𝟎 × 𝟏𝟎 𝟔 operation for each second then it is ok. • The following table contain the most common worst case Time complexity with the maximum recommended input size: Reference:
  • 9. Time Complexity in CP: CommentComplexityN e.g. Enumerating permutations𝑶 𝒏! , 𝑶(𝒏 𝟔 )≤ [10…11] e.g. DP TSP𝑶(𝟐 𝒏 × 𝒏 𝟐 )≤ [15…18] e.g. DP with bitmask technique, Perfect matching𝑶(𝟐 𝒏 × 𝒏)≤ [18…22] e.g. DP with 3 dimensions + O(n) loop𝑶(𝒏 𝟒)≤ 100 e.g. Floyd Warshall’s𝑶(𝒏 𝟑 )≤ 400 e.g. 2-nested loops + (a tree-related DS or binary search) 𝑶(𝒏 𝟐 𝒍𝒐𝒈 𝟐 𝒏)≤ 𝟐 × 𝟏𝟎 𝟑 e.g. Bubble/Selection/Insertion Sort𝑶(𝒏 𝟐 )≤ 𝟏𝟎 𝟒 e.g. Merge Sort, building Segment Tree𝑶(𝒏 𝒍𝒐𝒈 𝟐 𝒏)≤ 𝟏𝟎 𝟔 Most contest problem has n ≤ 1M (I/O bottleneck)𝑶 𝒏 , 𝑶 𝒍𝒐𝒈 𝟐 𝒏 , 𝑶(𝟏)≤ 𝟏𝟎 𝟖 Reference:
  • 10. Example 1: UVA - 441 - Lotto In the German Lotto you have to select 6 numbers from the set {1,2,...,49}. A popular strategy to play Lotto - although it doesn’t increase your chance of winning — is to select a subset S containing k (k > 6) of these 49 numbers, and then play several games with choosing numbers only from S. For example, for k = 8 and S = {1, 2, 3, 5, 8, 13, 21, 34} there are 28 possible games: [1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], ..., [3,5,8,13,21,34]. Your job is to write a program that reads in the number k and the set S and then prints all possible games choosing numbers only from S. Solve At:
  • 11. Example 1: UVA - 441 - Lotto Input The input file will contain one or more test cases. Each test case consists of one line containing several integers separated from each other by spaces. The first integer on the line will be the number k (6 < k < 13). Then k integers, specifying the set S, will follow in ascending order. Input will be terminated by a value of zero (0) for k. Output For each test case, print all possible games, each game on one line. The numbers of each game have to be sorted in ascending order and separated from each other by exactly one space. The games themselves have to be sorted lexicographically, that means sorted by the lowest number first, then by the second lowest and so on, as demonstrated in the sample output below. The test cases have to be separated from each other by exactly one blank line. Do not put a blank line after the last test case. Solve At:
  • 12. Example 1: UVA - 441 - Lotto Sample Input 7 1 2 3 4 5 6 7 0 Solve At: Sample Output 1 2 3 4 5 6 1 2 3 4 5 7 1 2 3 4 6 7 1 2 3 5 6 7 1 2 4 5 6 7 1 3 4 5 6 7 2 3 4 5 6 7
  • 13. Example 2: UVA - 10360 - Rat Attack Baaaam! Another deadly gas bomb explodes in Manhattan’s underworld. Rats have taken over the sewerage and the city council is doing everything to get the rat population under control. As you know, Manhattan is organized in a regular fashion with streets and avenues arranged like a rectangular grid. Waste water drains run beneath the streets in the same arrangement and the rats have always set up their nests below street intersections. The only viable method to extinguish them is to use gas bombs like the one which has just exploded. Solve At:
  • 14. Example 2: UVA - 10360 - Rat Attack However, gas bombs are not only dangerous for rats. The skyscrapers above the explosion point have to be evacuated in advance and so the point of rat attack must be chosen very carefully. The gas bombs used are built by a company called American Catastrophe Management (ACM) and they are sold under the heading of “smart rat gas”. They are smart because —when fired— the gas spreads in a rectangular fashion through the under street canals. The strength of a gas bomb is given by a number d which specifies the rectangular “radius” of the gas diffusion area. Solve At:
  • 15. Example 2: UVA - 10360 - Rat Attack For example, the figure shows what happens when a bomb with d = 1 explodes. Solve At:
  • 16. Example 2: UVA - 10360 - Rat Attack The area of interest consists of a discrete grid of 1025 × 1025 fields. Rat exterminator scouts have given a detailed report on where rat populations of different sizes have built their nests. You are given a gas bomb with strength d and your task is to find an explosion location for this gas bomb which extinguishes the largest number of rats. The best position is determined by the following criteria: 1) The sum of all rat population sizes within the diffusion area of the gas bomb (given by d) is maximal. 2) If there is more than one of these best positions then the location with the “minimal” position will be chosen. Positions are ordered first by their x coordinate and second by their y coordinate. Formally, given a location (x1, y1) on the grid, a point (x2, y2) is within the diffusion area of a gas bomb with strength d if the following equation holds: max(abs(x2 − x1), abs(y2 − y1)) ≤ d Solve At:
  • 17. Example 2: UVA - 10360 - Rat Attack Input The first line contains the number of scenarios in the input. For each scenario the first line contains the strength d of the gas bomb in the scenario (1 ≤ d ≤ 50). The second line contains the number n (1 ≤ n ≤ 20000) of rat populations. Then for every rat population follows a line containing three integers separated by spaces for the position (x, y) and “size” i of the population (1 ≤ i ≤ 255). It is guaranteed that position coordinates are valid (i.e., in the range between 0 and 1024) and no position is given more than once. Output For every problem print a line containing the x and y coordinate of the chosen location for the gas bomb, followed by the sum of the rat population sizes which will be extinguished. The three numbers must be separated by a space. Solve At:
  • 18. Example 2: UVA - 10360 - Rat Attack Sample Input 1 1 2 4 4 10 6 6 20 Solve At: Sample Output 5 5 30
  • 19. Bit manipulation • In competitive programing many problems need to utilize numbers as there bit representation. • The techniques of utilize the numbers bit representation is called Bit manipulation. • We will see in this part how to: 1. set or unset bit in number and check the state of a bit. 2. Know the right most bit. 3. Check if a number is power of 2. 4. Count the number of ones in binary representation. 5. Check if a number is odd or even or divide by 2. Reference:
  • 20. Bit manipulation • To set the i-th position bit in a number we can do an OR operator with a number that have a single 1 at the i-th position like that: num = num | (1 << i); • To unset the i-th bit in a number we must clear the i-th bit and leave all numbers as it by this: num = num & ~(1 << i); • To check the state of the i-th bit we can do AND operator on the number and the i-th bit like this: if(num & (1<<i)) • To filp the state of a bits in number we can use the XOR operator: num ^ mask; // if num=101 and mask= 011 the result // will be flipped at each 1 in the // mask and will be 110 Reference:
  • 21. Bit manipulation • We can use the last 3 techniques to represent a subset of element of a set by a number which the 0 or 1 in it means that we take or leave the elements. • E.g. the flowing set {1,3,9,7,5,4} and the subset {9,5,4} can be represented as the binary number 001011. • This number is called bit mask. Reference:
  • 22. Bit manipulation • To clear the right most digit in a number we can do & on the number and the number-1: x = num & num-1; • Check if the number is power of 2 we can clear the right most digit if the number became 0 then it is power of 2 (power of 2 contain single 1 in binary representation) and the only power of 2 that don’t have ones in it is 0 then we can do like that: if(x && !(x&x-1)) • To divide a number by 2 we can simply shift it to the right by 1 and to multiply it by 2 we can shift it to the left. • In general to divide by any x that power of 2 we can shift to the right by the log2 of x, and to multiply by any x that is power of 2 we can shift to the left by log2 of x. Reference:
  • 23. Bit manipulation • To determine if a number is odd or even we can simply check the first bit if it set: if(x & 1) cout <<”odd”; else cout<<“even”; • To count the number of ones effectively we can loop while the number is not 0 and clear the right most 1: while( x ) { x = x&(x-1); count++; } • To get the right most digit we can simply XOR the number with it after removing the right most digit: x ^ ( x & (x-1)) Reference:
  • 24. Example 3: Monk's Choice of Numbers Monk loves cakes! He visits the Binary Bakery to buy some of his favorite cheesecakes. The owner of the bakery, Bob, is a clever man. He does not want Monk to finish all his cheesecakes. Hence, he plays a game. The Monk is given N numbers and has to select K of these numbers. For each number that Monk chooses, he will get as many cheesecakes as the number of 1's in the Binary representation of the number i.e. the number of bits that are set. Help Monk find the maximum number of cakes that he can have. Solve At:
  • 25. Example 3: Monk's Choice of Numbers Input: The first line of input contains T. T test cases follow. First line of each test cases contains 2 space-separated integers N and K. The next line contains N space-separated integers. Output: For each test cases, print the answer in a new line. Constraints: 1 ≤ T ≤ 10 1 ≤ N ≤ 103 0 ≤ K ≤ N 0 ≤ Numbers ≤ 105 Solve At:
  • 26. Example 3: Monk's Choice of Numbers Sample Input 1 4 2 6 1 2 0 Solve At: Sample Output 3
  • 27. Example 4: Monk and his Friend Monk has a very good friend, Puchi. As weird as his name, are the games he plays. One fine day, they decided to play a game to test how diverse their choices are. Both of them choose exactly one integer each. Monk chooses an integer M and Puchi chooses an integer P. The diversity of their choices is defined as the number of bits whose status is different in the binary representation of M and P , i.e. , count of bits that are ,either set in M and unset in P or set in P and unset in M. Find the answer to their game. Solve At:
  • 28. Example 4: Monk and his Friend Input: First line contains T. T test cases follow. Each test case consists of 2 space-separated integers P and M. Output: Print the answer to each test case in a new line. Constraints: 1 ≤ T ≤ 104 0 ≤ M, P ≤ 1016 Solve At:
  • 29. Example 4: Monk and his Friend Sample Input 4 1 4 3 3 5 1 8 7 Solve At: Sample Output 2 0 1 4
  • 30. Thank you :) :) :)