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 :) :) :)

Acm aleppo cpc training ninth session

  • 1.
    ACM Aleppo CPCTraining Part 1 C++ Programming Concepts By Ahmad Bashar Eter
  • 2.
    The Priority QueueContainer • 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 QueueContainer • 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 QueueContainer • 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: MonkAnd 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: LittleMonk 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: LittleMonk and Goblet of Fire Sample Input 3 4 1 2 4 Solve At: Sample Output 11
  • 8.
    Bitset Container • Abitset 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 • Thesize 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 • Somebitset 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 • Somebitset 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 • Somebitset 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 • Tomake 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 • Someproblems 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 • Youcan 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 • Preprocessordirectives 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 weneed 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 • Sometimewe 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: UVA11553 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: UVA11553 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: UVA11553 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: Thepath 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: Thepath 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: Thepath in the colored field Sample Input 4 1223 2123 2213 3212 2 12 33 Sample Output 3 1
  • 29.