SlideShare a Scribd company logo
ACM Aleppo CPC Training
Part 1 C++ Programming Concepts
By Ahmad Bashar Eter
The Priority Queue Container
• Priority Queue is similar to queue, but with a one difference the
element with highest priority will be moved to the front of the queue.
Thus it is possible that when you enqueue an element at the back in the
queue, it can move to front because of its highest priority.
• In another words Priority queues are a type of container adaptors,
specifically designed such that its first element is always the greatest of
the elements it contains.
• This context is similar to a heap, where elements can be inserted at any
moment, and only the max heap element can be retrieved.
Reference:
The Priority Queue Container
• The Priority Queue are implemented as containers adaptors, which are
classes that use an encapsulated object of a specific container like
deque and vector.
• Priority Queue uses algorithm functions make_heap, push_heap and
pop_heap when needed to preserve the heap context to effectively
have the maximum element at the top of the heap orat the front of the
container.
Reference:
The Priority Queue Container
• Some member function of Queues are:
empty(): Returns true if the priority queue is empty and false if the
priority queue has at least one element. Its time complexity is
O(1).
pop(): Removes the largest element from the priority queue. Its time
complexity is O(logN) where N is the size of the priority queue.
push(): Inserts a new element in the priority queue. Its time complexity
is O(logN) where N is the size of the priority queue.
size(): Returns the number of element in the priority queue. Its time
complexity is O(1).
top(): Returns a reference to the largest element in the priority queue.
Its time complexity is O(1).
Reference:
Example 1: Monk And Champions League
Monk's favourite game is Football and his favourite club is "Manchester United".
Manchester United has qualified for the Champions League Final which is to be
held at the Wembley Stadium in London. So, he decided to go there and watch
his favourite team play. After reaching the stadium, he saw that many people
have lined up for the match tickets. He knows that there are M rows in the
stadium with different seating capacities. They may or may not be equal. The
price of the ticket depends on the row. If the row has K(always greater than 0)
vacant seats, then the price of the ticket will be K pounds(units of British
Currency). Now, every football fan standing in the line will get a ticket one by
one.
Given the seating capacities of different rows, find the maximum possible
pounds that the club will gain with the help of the ticket sales.
Solve At:
Example 1: Little Monk and Goblet of Fire
Input: The first line consists of M and N. M denotes the number of seating rows
in the stadium and N denotes the number of football fans waiting in the line to
get a ticket for the match.
Next line consists of M space separated integers X[1],X[2],X[3]....
X[M] where X[i] denotes the number of empty seats initially in the ith row.
Output:
Print in a single line the maximum pounds the club will gain.
Constraints:
1 <= M <= 1000000
1 <= N <= 1000000
1 <= X[i] <= 1000000
Sum of X[i] for all 1 <= i <= M will always be greater than N.
Solve At:
Example 1: Little Monk and Goblet of Fire
Sample Input
3 4
1 2 4
Solve At:
Sample Output
11
Bitset Container
• A bitset stores bits (elements with only two possible values).
• The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is eight times less than the smallest elemental type:
char).
• Each bit position can be accessed individually: for example, for a given
bitset named foo, the expression foo[3] accesses its fourth bit, just like a
regular array accesses its elements.
• Bitsets have the feature of being able to be constructed from and
converted to both integer values and binary strings. They can also be
directly inserted and extracted from streams in binary format.
Reference:
Bitset Container
• The size of a bitset is fixed at compile-time (determined by its template
parameter).
• To define a bitset:
bitset<100> x = 9;
string s = “1010011100”
bitset<100> y = s;
• With bitset you can use any bitwise operators(like <<,>>,&,^,|,~).
Reference:
Bitset Container
• Some bitset functions:
Reference:
Descriptionfunction
Access a bitoperator[]
Count bits in the bitsetcount
Return the size of bitsetsize
Return a bit value in the bitsettest
Test if any bit is setany
Test if no bit is setnone
Test if all bits are setall
Bitset Container
• Some bitset functions:
Reference:
Descriptionfunction
Set bits (make it 1)set
Reset bits(make it 0)reset
Flip bitsflip
Convert to stringto_string
Convert to unsigned long integerto_ulong
Convert to unsigned long longto_ullong
Bitset Container
• Some bitset functions:
Reference:
Descriptionfunction
Set bits (make it 1)set
Reset bits(make it 0)reset
Flip bitsflip
Convert to stringto_string
Convert to unsigned long integerto_ulong
Convert to unsigned long longto_ullong
Handling files
• To make the cin, cout streams read and write to a file you can use the
function freopen witch reopen a stream of data which allow you to
open a file to read from when using cin and open a file to write to when
using cout.
• This function take 3 parameters the first one is the file name to open,
the second one is “r” string or “w” string which specify how you will use
the file to read or write the last one is stdin or stdout which tell the
function to assign the file to the input stream(cin) or the output
stream(cout) .
• Eg: freopen(“input.txt”,”r”,stdin);
freopen(“output.txt”,”w”,stdout);
Reference:
C style IO
• In addition to c++ style IO we have the C style IO which consist of sacnf
and printf, these two functions IO in the C style. C style IO is much faster
than the C++ style this what made us interested in it.
• This two functions take 2 or more parameters the first parameter is a
string which contain the format or the description of the input or the
output, then the other parameters are the variables that we want to
print or scan.
• The formatting string may have a regular string and may have
commands started with % symbol which descript the variables type and
there display options.
Reference:
C style IO
• A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
The specifiers may be any one of this specifiers.
• %d mean decimal integer value.
• %ld mean decimal long integer value.
• %lld or %i64d mean decimal long long integer value.
• %f mean flotation point value.
• %s mean char array for C style strings value.
• %c mean one characher value.
Reference:
String Conversion
• Some problems give you the input as string and you need to extract the
values from it and some problems need you to combine two values next
to each other in some way.
• In this case you can solve the problem quickly if you can convert the
values to string and string to value.
• If you want to do this conversion you may use string stream.
• String stream behave like IO streams (cin, cout) but it reads and writes
to a string in the memory.
• To create string stream first you need to include <sstream> then create
stringstream object.
Reference:
String Conversion
• You can use the stringstream object to input using >> operator or to output
using << operator data from and to a string.
• The str method inside the stringstream give you the string which the stream is
writing to, also allow you to set a new string to read from.
• See this code snippet:
string s; int a; float b;
stringstream i("99.55"),o;
i >> b;
cout << b << endl;
o << 5 <<" "<< 9.5 << " abcdefg ";
cout << o.str()<<endl;
o >> a >> b >> s;
cout << a << endl << b << endl << s << endl;
Reference:
Preprocessor directives
• Preprocessor directives are lines included in the code of programs
preceded by a hash sign (#). These lines are not program statements but
directives for the preprocessor. The preprocessor examines the code
before actual compilation of code begins and resolves all these
directives before any code is actually generated by regular statements.
• These preprocessor directives extend only across a single line of code.
As soon as a newline character is found, the preprocessor directive is
ends. No semicolon (;) is expected at the end of a preprocessor
directive. The only way a preprocessor directive can extend through
more than one line is by preceding the newline character at the end of
the line by a backslash ().
Reference:
Macro definitions (#define)
• To define preprocessor macros we can use #define.
• Its syntax is: #define identifier replacement
• When the preprocessor encounters this directive, it replaces any
occurrence of identifier in the rest of the code by replacement. This
replacement can be an expression, a statement, a block or simply
anything. The preprocessor does not understand C++ proper, it simply
replaces any occurrence of identifier by replacement.
Reference:
Macro definitions (#define)
• When practicing in home online we may create our macros to help us
get our code ready fast.
• We may define a macro to represent a for loop like this:
#define rep(I,n) for(int i=0;i<n;i++)
• And we can use it like that:
rep(i,5){ cout<<i<<endl; }
• Before compiling the compiler will replace the rep(i,5) expression by the
for(int i=0;i<5;i++) so that we will end up having a for loop.
Reference:
Inline
• Sometimes we need to define a small function which it will be called so
many times.
• In this situation the calling overhead will be too much. To reduce this
overhead we can make this function inline.
• Inline functions are optimized so that the compiler can replace there
code by its calling operation.
• This will make the code much bigger but if the functions are small this
will make them run faster (no calling overhead).
Code Optimization
• Sometime we face a problem and we solve it with low order algorithm
but we still get TLE. In this case we need to optimize our code.
• This is some of the tips we need to have a good code:
1. Don’t use long long if you can.
2. Avoid using floating point numbers if you can, and if you must use
them consider the precision and use double instead of float.
3. If you have multi-dimensions array try make the last dimensions the
one to be accessed more frequently.
4. Try to stop your algorithm as soon as you find the solution or
eliminate parts of search space that you will not need them.
5. Use C style string and IO it may help.
Example 2: UVA 11553 Grid Game
Alice and Bob both have lots of candies but want more. They decide to play the
following turn-based game. They fill an nxn grid M with random integers. Alice
begins the game by crossing off an uncrossed row i of the grid. Now it’s Bob turn
and he crosses off an uncrossed column j of the grid.
At the end of Bob’s turn, Alice takes the number candies in the i-th row and j-th
column of M, call this value M(i; j), from Bob. (If M(i, j) is negative, then Alice
gives |M(i, j)| candies to Bob.) The game continues alternating turns from Alice
to Bob until the entire board is crossed off.
What is the largest amount of candies that Alice can win from Bob (or least
amount to lose if she cannot win) if both Alice and Bob play optimally?
Example 2: UVA 11553 Grid Game
Input
The first line of the input contains an integer t (1 t 20), the number of test cases.
Each test case starts with n (1 n 8), the size of the grid. Then follow n lines
containing n numbers separated by spaces describing M. We call the j-th number
on i-th line M(i; j) (􀀀 1000 M(i; j) 1000).
Output
For each test case, print the largest amount of candies that Alice can win from
Bob. If she cannot win,
print the negative number indicating the minimum number of candies she loses.
Example 2: UVA 11553 Grid Game
Sample Input
3
2
10 10
-5 -5
2
10 -5
10 -5
2
10 -5
-5 10
Sample Output
5
5
-10
Example 3: The path in the colored field
The square field consists of M M cells. Each cell is colored in one of three colors
(1,2,3). The initial state is chosen in one of the cells of color 1. In each step one
allowed to move one cell up, down, left or right remaining inside the field.
You are to define the minimal amount of steps one should make to get a cell of
color 3 independent on the initial state.
Note that the field contains at least one cell of color 1 and at least one cell of
color 3.
Example 3: The path in the colored field
Input
The input consists of several input blocks. The first line of each block contains
integer M, the size of
the field. Then there are M lines with colors of the cells.
Output
For each input block the output should consist of one line with the integer, the
minimal amount of
steps one should make to get a cell of color 3 independent on the initial state.
Example 3: The path in the colored field
Sample Input
4
1223
2123
2213
3212
2
12
33
Sample Output
3
1
Thank you :) :) :)

More Related Content

What's hot (20)

Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
C string
C stringC string
C string
University of Potsdam
 
The string class
The string classThe string class
The string class
Syed Zaid Irshad
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Strings
StringsStrings
Strings
Imad Ali
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
Dr. Md. Shohel Sayeed
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Anurag University Hyderabad
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
International Islamic University
 
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
Gautham Rajesh
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
Samsil Arefin
 
Strings
StringsStrings
Strings
Nilesh Dalvi
 
Python programming language
Python programming languagePython programming language
Python programming language
Ebrahim Shakhatreh
 
Python numbers
Python numbersPython numbers
Python numbers
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
C# Strings
C# StringsC# Strings
C# Strings
Hock Leng PUAH
 
String.ppt
String.pptString.ppt
String.ppt
ajeela mushtaq
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
Kelly Swanson
 

Similar to Acm aleppo cpc training ninth session (20)

Chapter 3 Expressions and Inteactivity
Chapter 3            Expressions and InteactivityChapter 3            Expressions and Inteactivity
Chapter 3 Expressions and Inteactivity
GhulamHussain142878
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
Frankie Jones
 
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docxLab Assignment #6, part 3 Time ConversionProgram Name lab.docx
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx
smile790243
 
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptxKMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
NelyJay
 
CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011
Deepak Singh
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
AnkurSingh656748
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
Praveen M Jigajinni
 
Chapter 2 Introduction to C++
Chapter 2             Introduction to C++Chapter 2             Introduction to C++
Chapter 2 Introduction to C++
GhulamHussain142878
 
Chapter02-S11.ppt
Chapter02-S11.pptChapter02-S11.ppt
Chapter02-S11.ppt
GhulamHussain638563
 
c++
c++c++
c++
Harsh Verma
 
1 Revision Tour
1 Revision Tour1 Revision Tour
1 Revision Tour
Praveen M Jigajinni
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
C++Basics.pdf
C++Basics.pdfC++Basics.pdf
C++Basics.pdf
AayushPoudel14
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
Ayesha Bhatti
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
MamataAnilgod
 
Chapter 3 Expressions and Inteactivity
Chapter 3            Expressions and InteactivityChapter 3            Expressions and Inteactivity
Chapter 3 Expressions and Inteactivity
GhulamHussain142878
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
Frankie Jones
 
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docxLab Assignment #6, part 3 Time ConversionProgram Name lab.docx
Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx
smile790243
 
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptxKMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
NelyJay
 
CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011CBSE Question Paper Computer Science with C++ 2011
CBSE Question Paper Computer Science with C++ 2011
Deepak Singh
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
MamataAnilgod
 

Recently uploaded (20)

Writing Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research CommunityWriting Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research Community
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
New syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdfNew syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdf
Arshad Shaikh
 
Drug Metabolism advanced medicinal chemistry.pptx
Drug Metabolism advanced medicinal chemistry.pptxDrug Metabolism advanced medicinal chemistry.pptx
Drug Metabolism advanced medicinal chemistry.pptx
pharmaworld
 
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANASTUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
Kweku Zurek
 
Decision Tree-ID3,C4.5,CART,Regression Tree
Decision Tree-ID3,C4.5,CART,Regression TreeDecision Tree-ID3,C4.5,CART,Regression Tree
Decision Tree-ID3,C4.5,CART,Regression Tree
Global Academy of Technology
 
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
How to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 ManufacturingHow to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 Manufacturing
Celine George
 
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Sandeep Swamy
 
The Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdfThe Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdf
Mirza Gazanfar Ali Baig
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted RegressionKNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
Global Academy of Technology
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
Unit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdfUnit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdf
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
ChatanBawankar
 
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
ChatanBawankar
 
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Ibrahim Tareq
 
THE FEMALE POPE IN SAINT PETER'S BASILICA
THE FEMALE POPE IN SAINT PETER'S BASILICATHE FEMALE POPE IN SAINT PETER'S BASILICA
THE FEMALE POPE IN SAINT PETER'S BASILICA
Claude LaCombe
 
Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate MilesResearch Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
mucomousamir
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
Protest - Student Revision Booklet For VCE English
Protest - Student Revision Booklet For VCE EnglishProtest - Student Revision Booklet For VCE English
Protest - Student Revision Booklet For VCE English
jpinnuck
 
New syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdfNew syllabus entomology (Lession plan 121).pdf
New syllabus entomology (Lession plan 121).pdf
Arshad Shaikh
 
Drug Metabolism advanced medicinal chemistry.pptx
Drug Metabolism advanced medicinal chemistry.pptxDrug Metabolism advanced medicinal chemistry.pptx
Drug Metabolism advanced medicinal chemistry.pptx
pharmaworld
 
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANASTUDENT LOAN TRUST FUND DEFAULTERS GHANA
STUDENT LOAN TRUST FUND DEFAULTERS GHANA
Kweku Zurek
 
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ..."Dictyoptera: The Order of Cockroaches and Mantises"  Or, more specifically: ...
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...
Arshad Shaikh
 
How to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 ManufacturingHow to Configure Subcontracting in Odoo 18 Manufacturing
How to Configure Subcontracting in Odoo 18 Manufacturing
Celine George
 
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Understanding-the-Weather.pdf/7th class/social/ 2nd chapter/Samyans Academy n...
Sandeep Swamy
 
The Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdfThe Splitting of the Moon (Shaqq al-Qamar).pdf
The Splitting of the Moon (Shaqq al-Qamar).pdf
Mirza Gazanfar Ali Baig
 
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
"Orthoptera: Grasshoppers, Crickets, and Katydids pptx
Arshad Shaikh
 
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted RegressionKNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
KNN,Weighted KNN,Nearest Centroid Classifier,Locally Weighted Regression
Global Academy of Technology
 
What are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS MarketingWhat are the Features & Functions of Odoo 18 SMS Marketing
What are the Features & Functions of Odoo 18 SMS Marketing
Celine George
 
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
Unit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdfUnit 4  Reverse Engineering Tools  Functionalities & Use-Cases.pdf
Unit 4 Reverse Engineering Tools Functionalities & Use-Cases.pdf
ChatanBawankar
 
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
Unit 1 Kali NetHunter is the official Kali Linux penetration testing platform...
ChatanBawankar
 
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Patent Law in Bangladesh Addressing Challenges in Pharmaceutical Innovation a...
Ibrahim Tareq
 
THE FEMALE POPE IN SAINT PETER'S BASILICA
THE FEMALE POPE IN SAINT PETER'S BASILICATHE FEMALE POPE IN SAINT PETER'S BASILICA
THE FEMALE POPE IN SAINT PETER'S BASILICA
Claude LaCombe
 
Education Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond IncomeEducation Funding Equity in North Carolina: Looking Beyond Income
Education Funding Equity in North Carolina: Looking Beyond Income
EducationNC
 
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate MilesResearch Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
mucomousamir
 
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptxQUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
QUIZ-O-FORCE 3.0 FINAL SET BY SOURAV .pptx
Sourav Kr Podder
 
Protest - Student Revision Booklet For VCE English
Protest - Student Revision Booklet For VCE EnglishProtest - Student Revision Booklet For VCE English
Protest - Student Revision Booklet For VCE English
jpinnuck
 

Acm aleppo cpc training ninth session

  • 1. ACM Aleppo CPC Training Part 1 C++ Programming Concepts By Ahmad Bashar Eter
  • 2. The Priority Queue Container • Priority Queue is similar to queue, but with a one difference the element with highest priority will be moved to the front of the queue. Thus it is possible that when you enqueue an element at the back in the queue, it can move to front because of its highest priority. • In another words Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains. • This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved. Reference:
  • 3. The Priority Queue Container • The Priority Queue are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container like deque and vector. • Priority Queue uses algorithm functions make_heap, push_heap and pop_heap when needed to preserve the heap context to effectively have the maximum element at the top of the heap orat the front of the container. Reference:
  • 4. The Priority Queue Container • Some member function of Queues are: empty(): Returns true if the priority queue is empty and false if the priority queue has at least one element. Its time complexity is O(1). pop(): Removes the largest element from the priority queue. Its time complexity is O(logN) where N is the size of the priority queue. push(): Inserts a new element in the priority queue. Its time complexity is O(logN) where N is the size of the priority queue. size(): Returns the number of element in the priority queue. Its time complexity is O(1). top(): Returns a reference to the largest element in the priority queue. Its time complexity is O(1). Reference:
  • 5. Example 1: Monk And Champions League Monk's favourite game is Football and his favourite club is "Manchester United". Manchester United has qualified for the Champions League Final which is to be held at the Wembley Stadium in London. So, he decided to go there and watch his favourite team play. After reaching the stadium, he saw that many people have lined up for the match tickets. He knows that there are M rows in the stadium with different seating capacities. They may or may not be equal. The price of the ticket depends on the row. If the row has K(always greater than 0) vacant seats, then the price of the ticket will be K pounds(units of British Currency). Now, every football fan standing in the line will get a ticket one by one. Given the seating capacities of different rows, find the maximum possible pounds that the club will gain with the help of the ticket sales. Solve At:
  • 6. Example 1: Little Monk and Goblet of Fire Input: The first line consists of M and N. M denotes the number of seating rows in the stadium and N denotes the number of football fans waiting in the line to get a ticket for the match. Next line consists of M space separated integers X[1],X[2],X[3].... X[M] where X[i] denotes the number of empty seats initially in the ith row. Output: Print in a single line the maximum pounds the club will gain. Constraints: 1 <= M <= 1000000 1 <= N <= 1000000 1 <= X[i] <= 1000000 Sum of X[i] for all 1 <= i <= M will always be greater than N. Solve At:
  • 7. Example 1: Little Monk and Goblet of Fire Sample Input 3 4 1 2 4 Solve At: Sample Output 11
  • 8. Bitset Container • A bitset stores bits (elements with only two possible values). • The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char). • Each bit position can be accessed individually: for example, for a given bitset named foo, the expression foo[3] accesses its fourth bit, just like a regular array accesses its elements. • Bitsets have the feature of being able to be constructed from and converted to both integer values and binary strings. They can also be directly inserted and extracted from streams in binary format. Reference:
  • 9. Bitset Container • The size of a bitset is fixed at compile-time (determined by its template parameter). • To define a bitset: bitset<100> x = 9; string s = “1010011100” bitset<100> y = s; • With bitset you can use any bitwise operators(like <<,>>,&,^,|,~). Reference:
  • 10. Bitset Container • Some bitset functions: Reference: Descriptionfunction Access a bitoperator[] Count bits in the bitsetcount Return the size of bitsetsize Return a bit value in the bitsettest Test if any bit is setany Test if no bit is setnone Test if all bits are setall
  • 11. Bitset Container • Some bitset functions: Reference: Descriptionfunction Set bits (make it 1)set Reset bits(make it 0)reset Flip bitsflip Convert to stringto_string Convert to unsigned long integerto_ulong Convert to unsigned long longto_ullong
  • 12. Bitset Container • Some bitset functions: Reference: Descriptionfunction Set bits (make it 1)set Reset bits(make it 0)reset Flip bitsflip Convert to stringto_string Convert to unsigned long integerto_ulong Convert to unsigned long longto_ullong
  • 13. Handling files • To make the cin, cout streams read and write to a file you can use the function freopen witch reopen a stream of data which allow you to open a file to read from when using cin and open a file to write to when using cout. • This function take 3 parameters the first one is the file name to open, the second one is “r” string or “w” string which specify how you will use the file to read or write the last one is stdin or stdout which tell the function to assign the file to the input stream(cin) or the output stream(cout) . • Eg: freopen(“input.txt”,”r”,stdin); freopen(“output.txt”,”w”,stdout); Reference:
  • 14. C style IO • In addition to c++ style IO we have the C style IO which consist of sacnf and printf, these two functions IO in the C style. C style IO is much faster than the C++ style this what made us interested in it. • This two functions take 2 or more parameters the first parameter is a string which contain the format or the description of the input or the output, then the other parameters are the variables that we want to print or scan. • The formatting string may have a regular string and may have commands started with % symbol which descript the variables type and there display options. Reference:
  • 15. C style IO • A format specifier follows this prototype: %[flags][width][.precision][length]specifier The specifiers may be any one of this specifiers. • %d mean decimal integer value. • %ld mean decimal long integer value. • %lld or %i64d mean decimal long long integer value. • %f mean flotation point value. • %s mean char array for C style strings value. • %c mean one characher value. Reference:
  • 16. String Conversion • Some problems give you the input as string and you need to extract the values from it and some problems need you to combine two values next to each other in some way. • In this case you can solve the problem quickly if you can convert the values to string and string to value. • If you want to do this conversion you may use string stream. • String stream behave like IO streams (cin, cout) but it reads and writes to a string in the memory. • To create string stream first you need to include <sstream> then create stringstream object. Reference:
  • 17. String Conversion • You can use the stringstream object to input using >> operator or to output using << operator data from and to a string. • The str method inside the stringstream give you the string which the stream is writing to, also allow you to set a new string to read from. • See this code snippet: string s; int a; float b; stringstream i("99.55"),o; i >> b; cout << b << endl; o << 5 <<" "<< 9.5 << " abcdefg "; cout << o.str()<<endl; o >> a >> b >> s; cout << a << endl << b << endl << s << endl; Reference:
  • 18. Preprocessor directives • Preprocessor directives are lines included in the code of programs preceded by a hash sign (#). These lines are not program statements but directives for the preprocessor. The preprocessor examines the code before actual compilation of code begins and resolves all these directives before any code is actually generated by regular statements. • These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is ends. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (). Reference:
  • 19. Macro definitions (#define) • To define preprocessor macros we can use #define. • Its syntax is: #define identifier replacement • When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement. Reference:
  • 20. Macro definitions (#define) • When practicing in home online we may create our macros to help us get our code ready fast. • We may define a macro to represent a for loop like this: #define rep(I,n) for(int i=0;i<n;i++) • And we can use it like that: rep(i,5){ cout<<i<<endl; } • Before compiling the compiler will replace the rep(i,5) expression by the for(int i=0;i<5;i++) so that we will end up having a for loop. Reference:
  • 21. Inline • Sometimes we need to define a small function which it will be called so many times. • In this situation the calling overhead will be too much. To reduce this overhead we can make this function inline. • Inline functions are optimized so that the compiler can replace there code by its calling operation. • This will make the code much bigger but if the functions are small this will make them run faster (no calling overhead).
  • 22. Code Optimization • Sometime we face a problem and we solve it with low order algorithm but we still get TLE. In this case we need to optimize our code. • This is some of the tips we need to have a good code: 1. Don’t use long long if you can. 2. Avoid using floating point numbers if you can, and if you must use them consider the precision and use double instead of float. 3. If you have multi-dimensions array try make the last dimensions the one to be accessed more frequently. 4. Try to stop your algorithm as soon as you find the solution or eliminate parts of search space that you will not need them. 5. Use C style string and IO it may help.
  • 23. Example 2: UVA 11553 Grid Game Alice and Bob both have lots of candies but want more. They decide to play the following turn-based game. They fill an nxn grid M with random integers. Alice begins the game by crossing off an uncrossed row i of the grid. Now it’s Bob turn and he crosses off an uncrossed column j of the grid. At the end of Bob’s turn, Alice takes the number candies in the i-th row and j-th column of M, call this value M(i; j), from Bob. (If M(i, j) is negative, then Alice gives |M(i, j)| candies to Bob.) The game continues alternating turns from Alice to Bob until the entire board is crossed off. What is the largest amount of candies that Alice can win from Bob (or least amount to lose if she cannot win) if both Alice and Bob play optimally?
  • 24. Example 2: UVA 11553 Grid Game Input The first line of the input contains an integer t (1 t 20), the number of test cases. Each test case starts with n (1 n 8), the size of the grid. Then follow n lines containing n numbers separated by spaces describing M. We call the j-th number on i-th line M(i; j) (􀀀 1000 M(i; j) 1000). Output For each test case, print the largest amount of candies that Alice can win from Bob. If she cannot win, print the negative number indicating the minimum number of candies she loses.
  • 25. Example 2: UVA 11553 Grid Game Sample Input 3 2 10 10 -5 -5 2 10 -5 10 -5 2 10 -5 -5 10 Sample Output 5 5 -10
  • 26. Example 3: The path in the colored field The square field consists of M M cells. Each cell is colored in one of three colors (1,2,3). The initial state is chosen in one of the cells of color 1. In each step one allowed to move one cell up, down, left or right remaining inside the field. You are to define the minimal amount of steps one should make to get a cell of color 3 independent on the initial state. Note that the field contains at least one cell of color 1 and at least one cell of color 3.
  • 27. Example 3: The path in the colored field Input The input consists of several input blocks. The first line of each block contains integer M, the size of the field. Then there are M lines with colors of the cells. Output For each input block the output should consist of one line with the integer, the minimal amount of steps one should make to get a cell of color 3 independent on the initial state.
  • 28. Example 3: The path in the colored field Sample Input 4 1223 2123 2213 3212 2 12 33 Sample Output 3 1
  • 29. Thank you :) :) :)