Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions 1244/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Tutorial for 1244 - Tiles

## Problem Summary

We need to find the number of ways to completely cover a $2 \times N$ board using the given 6 shapes without any overlapping tiles or empty spaces. Since the answer can be very large, we must output it modulo $10007$.

## Finding the Recurrence Relation

Let $A_n$ be the number of ways to perfectly tile a $2 \times n$ board.

**Base Cases:**

- $A_0 = 1$
- $A_1 = 1$ (1 way to place a single vertical shape)
- $A_2 = 2$ (2 ways: 2 vertical shapes or 2 horizontal shapes)
- $A_3 = 5$ (5 ways: 3 vertical, 2 horizontal and 1 vertical, 1 vertical and 2 horizontal, 2 L shaped together that cover 2\*3, same 2 L shaped together that cover 2\*3)

So, when we mathematically compress this infinite chain of possibilities, we get a recurrence relation:

$$A_n = 2A_{n-1} + A_{n-3}$$

## Matrix Exponentiation

Since $N$ can be up to $10^9$, calculating the sequence step-by-step using a basic loop will cause a **Time Limit Exceeded (TLE)**. We need to optimize this to $O(\log N)$ time using **Matrix Exponentiation**.

We can represent our recurrence relation using a $3 \times 3$ transition matrix $T$:

$$\begin{pmatrix} A_n \\ A_{n-1} \\ A_{n-2} \end{pmatrix} = \begin{pmatrix} 2 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix} \begin{pmatrix} A_{n-1} \\ A_{n-2} \\ A_{n-3} \end{pmatrix}$$

Given the base cases $A_0 = 1$, $A_1 = 1$, and $A_2 = 2$, we can calculate $A_n$ by raising the transition matrix $T$ to the power of $n-2$ and multiplying it by the base-case vector:

$$\begin{pmatrix} A_n \\ A_{n-1} \\ A_{n-2} \end{pmatrix} = T^{n-2} \begin{pmatrix} A_2 \\ A_1 \\ A_0 \end{pmatrix} = T^{n-2} \begin{pmatrix} 2 \\ 1 \\ 1 \end{pmatrix}$$

## Code Explanation

- **`multiply(A, B, mod)`**: This function takes two $3 \times 3$ matrices and multiplies them row-by-column. It applies the modulo arithmetic at every addition to prevent integer overflow.
- **`power(A, n, mod)`**: This function uses Binary Exponentiation. Instead of multiplying the matrix $n$ times, it repeatedly squares the matrix and halves the exponent. This is what brings the time complexity down from $O(N)$ to $O(\log N)$.
- **`tiles(n)`**: This handles the base cases directly. For larger $N$, it builds the transition matrix $T$, calls the `power` function to calculate $T^{n-2}$, and then extracts the final answer by multiplying the top row of the resulting matrix by our base cases ($A_2, A_1, A_0$).

## Complexity

- **Time Complexity:** $O(\log N)$ per test case. Matrix multiplication takes a constant $3^3$ operations, and we do this $\log_2(N)$ times.

## C++ Solution

```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long

#define fast_io ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)

vector<vector<ll>> multiply(vector<vector<ll>> A, vector<vector<ll>> B, ll mod)
{
vector<vector<ll>> C(3, vector<ll>(3));
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = 0;
for (int k = 0; k < 3; k++)
{
C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;
}
}
}
return C;
}

// Iterative matrix exponentiation (binary exponentiation)
vector<vector<ll>> power(vector<vector<ll>> A, ll n, ll mod)
{
vector<vector<ll>> result = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; // identity matrix
while (n > 0)
{
if (n & 1)
result = multiply(result, A, mod);
A = multiply(A, A, mod);
n >>= 1;
}
return result;
}

ll tiles(ll n, ll mod = 1e4 + 7)
{
// Base cases
if (n == 0) return 1;
else if (n == 1) return 1;
else if (n == 2) return 2;

// Transition matrix
vector<vector<ll>> T = {{2, 0, 1}, {1, 0, 0}, {0, 1, 0}};

// Fast-forward matrix to N-2 steps
vector<vector<ll>> Tn = power(T, n - 2, mod);

// Calculate final answer using top row and base cases: (Tn[0][0]*A_2 + Tn[0][1]*A_1 + Tn[0][2]*A_0)
ll ans = (2 * Tn[0][0] + 1 * Tn[0][1] + 1 * Tn[0][2]) % mod;
return ans;
}

void Rupalisaurus()
{
ll n;
cin >> n;
cout << tiles(n) << "\n";
}

int32_t main()
{
fast_io;

ll t, tc = 0;
if (cin >> t) {
while (t--)
{
cout << "Case " << ++tc << ": ";
Rupalisaurus();
}
}
return 0;
}
```
142 changes: 142 additions & 0 deletions 1360/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# Tutorial for Skyscraper

## Problem Summary

We are given $N$ tasks (or skyscraper building phases), each characterized by a starting time $a$, a duration $b$, and a profit or value $c$. The task finishes at time $a + b$. We want to choose a subset of non-overlapping tasks such that the total profit is maximized. A new task can start exactly at or after the finish time of a chosen task.

This is a classic variation of the **Weighted Job Scheduling** problem.

## Finding the DP State and Recurrence Relation

To solve this, we first sort the tasks based on their starting times in ascending order.

Let `DP[i]` be the maximum profit we can achieve by considering a subset of tasks from index $i$ to $N-1$.

**Base Case:**

- `DP[N] = 0` (If there are no tasks left to consider, the profit is 0).

For any task at index $i$, we have two choices:

1. **Skip the current task:** The maximum profit will just be the best we can do using the remaining tasks, which is `DP[i+1]`.
2. **Take the current task:** We gain its profit $c$, but we cannot take any tasks that overlap with it. We must find the next valid task `ind` that starts on or after $a + b$. The profit would then be $c + DP[ind]$.

So,

$$DP[i] = \max(DP[i+1], c_i + DP[ind])$$

## Optimizing with Binary Search

Finding the next non-overlapping task (`ind`) using a simple `for` loop would take $O(N)$ time per state, leading to a Time Limit Exceeded (TLE) overall time complexity of $O(N^2)$.

Since we have already sorted our tasks by their starting times, We can optimize the search for `ind` down to $O(\log N)$ using **Binary Search** (`lower_bound` in C++).

For a task $i$ ending at $nxtfloor = a_i + b_i$, we query the sorted start times to find the first index `ind > i` where $start[ind] \ge nxtfloor$.

## Code Explanation

- **`choto(v)`**: A macro for `sort(v.begin(), v.end())`. Since our vectors are structured as `{start, duration, profit}`, sorting the 2D vector automatically sorts all tasks based on their starting times.
- **`start` array**: We isolate the starting times of all tasks into a single 1D vector. This provides a clean array to run our binary search on.
- **`lower_bound(...) - start.begin()`**: This effectively acts as our binary search. It looks from `i + 1` to the end of the `start` array for the first task that begins on or after `nxtfloor` ($a + b$). It returns the index `ind` of that task.
- **`dp` array**: We iterate backwards from $N-1$ down to 0, populating our $DP$ table using the recurrence relation. `dp[0]` will ultimately hold the maximum profit considering all tasks.

## Complexity

- **Time Complexity:** $O(N \log N)$ per test case. Sorting the array takes $O(N \log N)$. Populating the DP array takes $N$ steps, and each step performs a binary search taking $O(\log N)$ time.
- **Space/Memory Complexity:** $O(N)$ for storing the tasks in the 2D vector, the 1D `start` array, and the 1D `dp` array.

## C++ Solution

```cpp
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define pi acos(-1.0)
#define pb push_back
#define sqrt(x) sqrtl(x)
#define pll pair<ll, ll>
#define NO cout << "NO" << endl
#define YES cout << "YES" << endl
#define choto(x) sort((x).begin(), (x).end())
#define boro(x) sort((x).rbegin(), (x).rend())
#define all(x) (x).begin(), (x).end()
#define in(x) \
for (auto &it : x) \
cin >> it;
#define allout(x) \
for (auto &it : x) \
cout << it << " "; \
cout << endl
#define out(y, a, n) \
for (ll i = a; i <= n; i++) \
cout << y[i] << " "; \
cout << endl
#define vsum(x) accumulate((x).begin(), (x).end(), 0LL)
#define vec2d(name, n, m, val) vector<vector<ll>>(name)((n), vector<ll>((m), (val)))
#define fix(n, val) fixed << setprecision(n) << val
#define padding0(n, val) setw(n) << setfill('0') << val
#define dbug(x) cout << #x << " -> " << x << endl;
#define ff first
#define ss second
#define fast_io ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)

void Rupalisaurus()
{
ll n;
cin >> n;
vec2d(v, n, 3, 0);
for (ll i = 0; i < n; i++)
{
cin >> v[i][0] >> v[i][1] >> v[i][2];
}

// Sort tasks by start time
choto(v);

vector<ll> start(n);
for (ll i = 0; i < n; i++)
{
start[i] = v[i][0];
}

// DP array to store max profit from index i to n-1
vector<ll> dp(n + 1, 0);
ll a, b, c;
ll nxtfloor;
ll ind;

// Process from right to left
for (ll i = n - 1; i >= 0; i--)
{
a = v[i][0];
b = v[i][1];
c = v[i][2];

nxtfloor = a + b; // Finish time

// Binary search to find the next compatible task
ind = lower_bound(start.begin() + i + 1, start.end(), nxtfloor) - start.begin();

// Transition: max(Skip current, Take current + max profit from next valid)
dp[i] = max(dp[i + 1], c + dp[ind]);
}

cout << dp[0] << endl;
}

int32_t main()
{
fast_io;

ll t, tc = 0;
if (cin >> t) {
while (t--)
{
cout << "Case " << ++tc << ": ";
Rupalisaurus();
}
}
return 0;
}
```