## Introduction

**The National Olympiad in Informatics — Philippines is an informatics olympiad where contestants solve algorithmic tasks by writing correct and efficient programs.**

Let’s try to break that down.

- National means everyone in the Philippines can join this contest.
- Informatics is the science of studying efficient methods for storing, processing, and retrieving data.
- An olympiad is a major contest in a particular game, sport or scientific subject.

Like many scientific olympiads, the contestants (i.e. you!) are given a number of tasks to solve within a limited amount of time. In math olympiads, contestants are often given problems that look not unlike the following:

There are an infinite number of positive integers such that is divisible by . Find the th one.

These types of problems are all well and good, but a sufficiently determined contestant might elect to start bashing every case; he or she might write down every starting from , check whether each satisfies the condition by trial and error — and eventually arrive at the correct answer! In this case, the contestant did not even have to think at all, and missed out on the crucial insights that would have make the solution to this problem much more palatable.

The NOI.PH, as an informatics olympiad, is not all too different from these math competitions or olympiads; in that the tasks often require insights, and these insights have to be synthesized to produce a final answer. The crucial distinction is that, in the NOI.PH, your final answer is a program, not a number.

If the same problem were to be given in the NOI.PH, it might be phrased like so:

There are an infinite number of positive integers such that is divisible by . Find the th one.

Notice the critical difference: we are being asked to find the th such number instead of, say, the th one. As a contestant, your goal is to submit a program that takes in any integer , satisfying certain constraints (more on that later), as input, and gives the correct answer for that particular , as output. Your program might be given , or , or , or some other number; and your program must always give the correct answer, and do so quickly enough.

By requiring contestants to submit a program instead of a number, the contestants solve the general case of the task and thus demonstrate their knowledge of the insights necessary to solve it! While a contestant might simply write a program that tries every possible from onwards to find the th one, this will run noticeably slower than someone who, say, has found a closed-form formula or derived a fast algorithm to solve the same. For large enough , the solution that simply tries all different sums will eventually take very long, and so it will exceed the time limit and, like a wrong answer, will not be credited full marks. Of course, the beauty of the NOI.PH is that even suboptimal programs can sometimes score partial points — but we’ll cover the specifics of that later.

## Your First Task

Now, let’s get our hands dirty, by solving an actual informatics task!

Note that this section assumes knowledge of basic programming, such as arrays and nested loops, and a little bit of C++ syntax. If you have no prior experience with these concepts or simply want a refresher, you are invited to attempt the C++ for Competitive Programming tutorial, which also serves as a softer and more comprehensive version of this guide.

We will be tackling the task Azalea, and we will go through the different parts of the task and attempt some solutions. Along the way, we will also discuss some features of the HackerRank platform in particular, on which the NOI.PH contests are hosted for the time being.

## The Problem Statement

All tasks begin with a **problem statement**. The problem statement situates the task, and usually, although not necessarily, comes accompanied with a story. As a competitive programmer, it is your job to dissect the problem statement and figure out exactly what it is asking. Sometimes, this is easy; the statement is no-nonsense and gets straight to the point (e.g. A Simple Problem!). Other times, the statement can be hilariously obnoxious and riddled with unnecessary background (e.g. Meteor Garden Garden).

The problem statement for Azalea reads as follows:

A small quaint town, known for its annual springtime azalea festival, begins preparations for the new season. The organizers have arranged azalea shrubs in a horizontal row; the shrub, from the left, has flowers, and is labelled .

The festival lasts days. In the day, as per tradition, the number of flowers between shrubs labelled to , inclusive, are counted, and the townspeople gather together and prepare that many dishes for the festivities of that day.

After the festivities of each day, the local gardener comes and waters every shrub, and so a single new flower blooms in each one of them.

The festival has not yet begun, but the townspeople want to know how many dishes they will need to prepare for each day, so they can start sourcing for ingredients. Can you help them?

The statement is quite long, and contains quite a number of irrelevant details. Can we whittle down the length and express it in a more concise way?

A good place to start is to try to list down the events in point form, so we can get a clearer picture of what we have to do:

- There are shrubs, with the shrub labelled having flowers.
- There are days:
- In the th day, the number of dishes prepared is equal to the number of flowers between shrubs to , inclusive.
- In the th night, a gardener comes and waters all the shrubs, so they each gain one flower.

- We need to determine the number of dishes prepared for each of the days.

Much better!

Remember that , , and all the , and are variables and our program must produce the correct result regardless of the values of these numbers!

## The Input and The Output

Now that we know what to do, let’s look at the input format and output format, and the sample input and sample output.

The input format reads as follows:

The first line contains a single integer , the number of test cases to handle.

Each test case begins with two integers and on a single line, the number of azalea shrubs and the number of days the azalea festival lasts, respectively.

The next line contains integers, , the number of flowers in each shrub.

The next lines each contain two integers. Specifically, the line among these contains and , describing the range of shrubs whose flowers will be counted for the day.

The output format reads as follows:

For each test case, output integers, separated by spaces, on a single line. The integer should contain the number of dishes the townspeople must prepare for the day.

If it looks rather complicated, don’t despair; all it is really telling us is the format our program should receive the input, and the format our program should report the output. We will see in a short while what all of this means! For now, take special care for the output format; everything our program outputs is considered “output”, so if you output some debugging statements like “Please enter T” or print something like: “The answer is: ”, this will be considered as part of your answer, and because it does not satisfy the output format, it will be marked wrong, even if your answer is otherwise correct!

Some tasks, such as this one, contain multiple test cases, which basically means your program should solve the task multiple times, with different inputs. Each test case describes a separate instance of the task; however, your program must correctly process all test cases in a single input within the given time limit.

Let’s take a look at the sample input:

1 2 3 4 5 6 7 8 9 |
2 6 3 1 1 2 1 9 9 3 5 1 6 2 2 10 1 1 2 3 4 5 6 7 8 9 10 1 10 |

And the sample output:

1 2 |
12 29 3 55 |

The sample input gives an instance of some valid input that your program might be given, and the sample output gives a correct response to the given sample input. To see that, let’s recall the input format.

1 2 3 4 5 6 7 8 9 |
2 6 3 1 1 2 1 9 9 3 5 1 6 2 2 10 1 1 2 3 4 5 6 7 8 9 10 1 10 |

The first line of input contains a single integer , which is the number of test cases; in this case, we know that , so we have 2 test cases to handle.

1 2 3 4 5 6 7 8 9 |
2 6 3 1 1 2 1 9 9 3 5 1 6 2 2 10 1 1 2 3 4 5 6 7 8 9 10 1 10 |

Each test case begins with two integers, and ; in this case, we know that the first test case has and . The next line contains integers, which contains the values of . Then, the next lines contain two integers; the first line among these contains , , the second , , and the third , .

1 2 3 4 5 6 7 8 9 |
2 6 3 1 1 2 1 9 9 3 5 1 6 2 2 10 1 1 2 3 4 5 6 7 8 9 10 1 10 |

The remaining lines describe the second test case; in this case, we know that the second test case has and . The next line contains integers, which contains the values of . Then, the next line contains two integers, and .

Consider the first test case. We can, in fact, substitute the values of the variables into our condensed problem statement:

- There are 6 shrubs:
- The 1st shrub has 1 flower.
- The 2nd shrub has 1 flower.
- The 3rd shrub has 2 flowers.
- The 4th shrub has 1 flower.
- The 5th shrub has 9 flowers.
- The 6th shrub has 9 flowers.

- There are 3 days:
- In the 1st day:
- The number of dishes prepared is equal to the number of flowers between shrubs 3 to 5, inclusive.
- Afterwards, the gardener comes and waters all the shrubs, so they each gain one flower.

- In the 2nd day:
- The number of dishes prepared is equal to the number of flowers between shrubs 1 to 6, inclusive.
- Afterwards, the gardener comes and waters all the shrubs, so they each gain one flower.

- In the 3rd day:
- The number of dishes prepared is equal to the number of flowers between shrubs 2 to 2, inclusive.
- Afterwards, the gardener comes and waters all the shrubs, so they each gain one flower.

- In the 1st day:
- We need to determine the number of dishes prepared for each of the 3 days.

## The Explanation Section

The explanation of the sample input is usually given in the **explanation section**, and indeed, this is precisely what we get:

In the first test case, there are shrubs, and the springtime azalea festival lasts for days.

Before the festival begins, the shrubs have , , , , , and flowers from left to right.

In the day, the flowers between shrubs and , inclusive, are counted. There are flowers, and so the townspeople prepare dishes for the festivities of the day.

After the festivities of the day, the local gardener comes and waters each shrub. Now, the shrubs have , , , , , and flowers from left to right.

In the day, the flowers between shrubs and , inclusive, are counted. There are flowers, and so the townspeople prepare dishes for the festivities of the day.

After the festivities of the day, the local gardener comes and waters each shrub. Now, the shrubs have , , , , , and flowers from left to right.

In the and final day, the flowers between shrubs and , inclusive, are counted. There are flowers, and so the townspeople prepare dishes for the festivities of the day.

After the festivities of the day, the local gardener comes and waters each shrub. Now, the shrubs have , , , , , and flowers from left to right.

The festivites are over, and we report the number of dishes the townspeople must prepare each day:

1. The townspeople must prepare dishes on the day.

2. The townspeople must prepare dishes on the day.

3. The townspeople must prepare dishes on the day.Similar analysis can be performed for the second test case.

The explanation situates the problem in terms of “numbers”, instead of variables. More precisely, it explains the sample input, and how we can derive the sample output if we were given the sample input. Of course, the reasoning given in the explanation is non-general; it applies only to the given sample input, and usually does not give many insights about how the problem can be solved in the general case.

It is good practice to look at the explanation and see that your understanding of the problem is correct; sometimes, you may encounter ambiguous statements, and you can rely on the explanation to see whether you have read the problem correctly, or if you have missed some important detail. In this case, it may not be as important, but in other problems you may find this explanation very much helpful.

## The Constraints

Now that that’s clear, we can discuss the constraints:

Subtask 1(24 points)

Subtask 2(34 points)

The sum of in a test case does not exceed .

Subtask 3(42 points)

The constraints communicate to us the maximum and minimum possible values the variables in the problem statement can assume. For example, in this case, we have , which means that there will be at least test case and at most test cases. This makes sense, because our program cannot be expected to, say, handle test cases, and still run within the time limit! Some constraints are straightforward; between and , for example; while others are more cryptic, like “the sum of in a test case does not exceed “. Sometimes, a cryptic constraint reveals a property that can be exploited to write an efficient enough solution.

## Time Limit

Speaking of efficient solutions, note that all programs have a time limit within which they are expected to read all the input, process the input, write all the output, and terminate. It must be able to solve all the test cases in the input within the time limit. The time limit is standard for all NOI.PH problems, and, unless explicitly noted otherwise, are:

- 2 seconds for C++;
- 4 seconds for Java;
- 10 seconds for Python.

The time limit is more relaxed for Java and Python, as these languages are inherently slower; however, generally speaking, *if the algorithm itself is sub-optimal*, it will fail regardless of which language you code it on! Remember that the problems in the NOI.PH are always *algorithmic in nature*, and code is simply our way of *expressing our algorithm*. By its nature, a more efficient algorithm almost always trumps a better implementation of a bad algorithm!

In general, we can perform about “cheap” operations, such as addition or bitwise operations, within the time limit, and about “expensive” operations, such as multiplication or division, within the same. Knowing exactly how much processing power you can squeeze from your program is an ability that is learned through practice, and you will eventually have a good intuition for it!

## The Subtasks

Notice that there are subtasks, each with a varying number of points. While there are constraints that are common to all subtasks, such as or , there are constraints that are imposed to some subtasks but not others; for example, subtask imposes that is only up to , whereas subtasks and impose that is up to . This allows us to score partial points! For example, we might have a program that is correct and runs within the time limit if is just 2000, but produces a wrong answer or exceeds the time limit if it is greater than .

## The Code Editor

That said, we can now attempt to solve this problem.

HackerRank has a built-in code editor, provided with each problem, where we can write our code. By default, it contains the following:

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; } |

If you are just starting out, this can be very helpful! You do not need to download a compiler or an IDE just yet; for simpler tasks, you will find that the online code editor will suffice.

HackerRank provides a number of tools you can use to test your code. For example, hitting automatically compiles and runs the code against the sample input as described in the problem statement, and tells you whether your output is correct or not, or whether your code took too long, crashed, or could not even compile (in the last case, HackerRank also helpfully informs you of the error). You can also test against your own input by using the built-in function to Test against custom input. Using this feature, you can give your program any input, and HackerRank essentially serves as a compiler. Note that this option **does not** check the correctness of your output or even the validity of input; this means you can use the function to test your program against anything, just as you would a normal compiler.

When you are done with your solution, and you think that it is correct, you can simply hit and watch, in real time, the results as your program is tested against the input.

## Submission 1

All that said, let’s see what happens when we code the most straightforward solution.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> using namespace std; int a[100005]; int ans[100005]; int main() { int tc, n, d, l, r, sum; cin >> tc; for (int t = 0; t < tc; t++) { cin >> n >> d; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= d; i++) { cin >> l >> r; sum = 0; for (int j = l; j <= r; j++) //compute the number of flowers from the lth shrub to the rth shrub sum += a[j]; ans[i] = sum; //store the answer for (int j = 1; j <= n; j++) //increase the number of flowers in each shrub by 1 a[j]++; } for (int i = 1; i <= d; i++) { if (i != 1) //print space before every integer, except the first cout << ' '; cout << ans[i]; } cout << '\n'; } } |

We hit , and… um, wow! It worked on the first try! (Note: this is rare and doesn’t usually happen, especially when starting out. You will normally encounter a number of compilation issues before you can get it to work. Learning how to debug is important!)

Congratulations, you passed the sample test case.

Click the

Submit Codebutton to run your code against all the test cases.

123456789 26 31 1 2 1 9 93 51 62 210 11 2 3 4 5 6 7 8 9 101 10

12 12 29 355

12 12 29 355

Now, we hit to submit our code.

Submitted a few seconds ago

Score: 24.00

Status: Terminated due to timeout✓ Test Case #0

✓ Test Case #1

⏱ Test Case #2

⏱ Test Case #3

Alas! Our code successfully solves the first subtask, scoring 24 points, but it fails for the other two, giving a “terminated due to timeout” verdict. “What gives? It worked on the sample test cases!” I hear you exclaim.

## Submission 2

Let’s analyze how many operations our code takes. It is clear that the majority of the work is happening in the two nested loops; one looping from to , and, within that, two loops; one looping from to and another looping from to .

We know that, for the second test case, and are both up to . Therefore, even if we ignore the loop going from to , we already have iterations; this is significantly greater than , and so we can wager that our program will probably not finish in time. This is even ignoring the fact that we have up to test cases in one input!

We will need to optimize our algorithm, by making some observations.

The bottleneck in our program is the loop from to . Can we somehow eliminate this loop?

Yes, we can! We need to notice that, because the gardener waters all the plants every day, at the th day, each shrub simply has extra flowers than original.

The other insight is that we can count these extra flowers separately; there are shrubs between shrubs and , inclusive, and each of them has extra flowers. So, the total number of extra flowers is simply , and we can simply add this to the total count of flowers!

We now have the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <iostream> using namespace std; int a[100005]; int ans[100005]; int main() { int tc, n, d, l, r, sum; cin >> tc; for (int t = 0; t < tc; t++) { cin >> n >> d; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= d; i++) { cin >> l >> r; sum = 0; for (int j = l; j <= r; j++) //compute the original number of flowers from the lth shrub to the rth shrub sum += a[j]; sum += (r-l+1)*(i-1); //add the extra flowers ans[i] = sum; //store the answer } for (int i = 1; i <= d; i++) { if (i != 1) //print space before every integer, except the first cout << ' '; cout << ans[i]; } cout << '\n'; } } |

How long does this run? At worst, we could still have and for all ; then, we will still have iterations. But wait! Remember that the second subtask has an extra suspicious constraint — the sum of is at most . Could this perhaps save us here?

A more nuanced count on the number of iterations our loop actually performs can be of help. Note that we loop from to , so we consider only values in the th day. So, summing this over all days, the inner loop actually iterates times! If we note that is equal to because , and that there are exactly occurrences of in this sum, then we can rewrite this as: . But the sum of all the is at most , and so the above sum is actually only at most ; that means, the inner loop only performs at most iterations across all days for each test case!

This analysis should convince us that this program will finish in time. And indeed, submitting it gives…

Submitted a few seconds ago

Score: 24.00

Status: Wrong Answer✓ Test Case #0

✓ Test Case #1

✗ Test Case #2

⏱ Test Case #3

## Submission 3

…wrong answer? What’s up with that? Surely the problem setter must have an incorrect model solution!

In fact, there are a number of very subtle mistakes in our code, which can be summed up in a word: overflow. In our code, we used the `int`

data type, which in C++ can store any integer value between and , or slightly more than . But what is the maximum possible answer?

It is not immediately obvious, but it can actually exceed this! If we have and , and on the last day we have and , then the total number of extra flowers across all shrubs, according to our previous formula, is . That’s , which is almost ; thus, we get integer overflow! The problem setter must have been very sneaky, and, anticipating this, added this test case in!

To remedy this, we simply have to use a larger data type, such as `long long int`

, which can store values between and , which is much larger than the largest possible answer. The details of this are more nuanced, and it is not enough to simply change the types of sum and ans in the above code; we must also change and , or perform a typecast when we do the multiplication `(r-l+1)*(i-1)`

. You are encouraged to peruse this to find out more details. (You need to register here first before you can access the link.)

Anyway, after fixing these bugs, we now have the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> using namespace std; int a[100005]; long long int ans[100005]; int main() { int tc, n, d, l, r; long long int sum; cin >> tc; for (int t = 0; t < tc; t++) { cin >> n >> d; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= d; i++) { cin >> l >> r; sum = 0; for (int j = l; j <= r; j++) //compute the original number of flowers from the lth shrub to the rth shrub sum += a[j]; sum += ((long long int)(r-l+1))*(i-1); //add the extra flowers, cast to long long int to avoid overflow ans[i] = sum; //store the answer } for (int i = 1; i <= d; i++) { if (i != 1) //print space before every integer, except the first cout << ' '; cout << ans[i]; } cout << '\n'; } } |

Now, we smash that button and get:

Submitted a few seconds ago

Score: 58.00

Status: Terminated due to timeout✓ Test Case #0

✓ Test Case #1

✓ Test Case #2

⏱ Test Case #3

Eureka! We’ve got the second subtask.

## Submission 4+

The timeout on the third is rather expected; as we mentioned earlier, in the worst case, we could still have and for all , causing our program to require iterations. The final subtask has no restrictions on , so we can’t perform the reductions earlier to show that this worst case is impossible. Indeed, the worst case is very much possible — and you can expect, as a contestant, that the problem setter has also added this worst case, or something similar, as one of the test cases for the final subtask.

So, are we doomed? Or is there hope for us yet?

Luckily, there is (and of course there is, because the problem setter must have some correct solution), and it involves a very clever trick.

Let’s create an array of length , where . We can generate this array very efficiently, using only one loop; we let , then for all , we can do . Thus we can generate this array with only about operations.

Now, suppose we want to find the sum of . Currently, we do that using a loop, which takes operations; that’s too slow! Notice, however, that the sum is equal to: , because all the terms cancel themselves out!

But then this is equal to , using our earlier definition for . And we already know how to generate efficiently; not to mention, we only ever have to generate it once, at the beginning, because we’ve already reduced the problem to the case where the values in never change. So, we can eliminate the nested loop entirely!

Actually coding this is left as an exercise for you; while you code it, take into consideration any possible corner cases or sources of bugs. Rest assured that it will be worth it; there is no joy just the same as seeing this:

Submitted a few seconds ago

Score: 100.00

Status: Accepted✓ Test Case #0

✓ Test Case #1

✓ Test Case #2

✓ Test Case #3

Except maybe the smell of azalea flowers in spring. But that’s besides the point.

## Conclusion

Hopefully, the in-depth analysis of this problem and the corresponding discussions have allowed you to develop a more comprehensive understanding of what the NOI.PH is, what it entails, the contest format and platform, the types of problems you will encounter, as well as the thought processes and the kinds of insights necessary to solve these types of tasks. If you want to learn more, or try your hand at solving some tasks from past NOI.PH contests, make sure to check out:

- the Prepare page of the official NOI.PH website,
- the repository of past NOI.PH problems,
- the official training website,
- C++ for Competitive Programming,
- and all the other resources available online!

But you don’t have to be alone in your quest for greatness. There’s even a Discord **chat room** for Filipino competitive programming enthusiasts. Email **[email protected]** for more information.

We hope you found this whole tutorial useful, and we wish you the best of luck in the NOI.PH!