Greedy Algorithms & Number Theory
Local choice + CP-র গণিত
1. Greedy — Local Optimum
Greedy algorithm প্রতিটি step-এ সবচেয়ে ভালো local choice নেয় — backtracking ছাড়াই। Global optimum দেয় শুধু তখনই যখন প্রমাণ-যোগ্য।
2. Activity Selection (Classic Greedy)
#include <stdio.h>
#include <stdlib.h>
typedef struct { int s, e; } Act;
int cmp(const void *a, const void *b) {
return ((const Act*)a)->e - ((const Act*)b)->e;
}
int main(void) {
Act a[] = { {1,4}, {3,5}, {0,6}, {5,7}, {3,9}, {5,9}, {6,10}, {8,11} };
int n = 8;
qsort(a, n, sizeof a[0], cmp);
int last = -1, picked = 0;
for (int i = 0; i < n; i++) {
if (a[i].s >= last) {
printf("(%d, %d)\n", a[i].s, a[i].e);
last = a[i].e;
picked++;
}
}
printf("total = %d\n", picked);
return 0;
}
প্রমাণ: যদি optimal solution আলাদা activity দিয়ে শুরু করে, তাকে আমাদের প্রথম choice-এ swap করা যায় — ফলাফল কমবে না।
3. GCD, LCM, Extended Euclid
#include <stdio.h>
long gcd(long a, long b) { return b ? gcd(b, a % b) : a; }
long lcm(long a, long b) { return a / gcd(a, b) * b; }
// returns gcd; sets x, y such that a*x + b*y = gcd
long egcd(long a, long b, long *x, long *y) {
if (b == 0) { *x = 1; *y = 0; return a; }
long x1, y1;
long g = egcd(b, a % b, &x1, &y1);
*x = y1;
*y = x1 - (a / b) * y1;
return g;
}
int main(void) {
printf("gcd(48, 36) = %ld\n", gcd(48, 36));
printf("lcm(4, 6) = %ld\n", lcm(4, 6));
long x, y, g = egcd(30, 18, &x, &y);
printf("egcd(30, 18): gcd=%ld, x=%ld, y=%ld\n", g, x, y);
printf("check: 30 * %ld + 18 * %ld = %ld\n", x, y, 30*x + 18*y);
return 0;
}
4. Sieve of Eratosthenes
#include <stdio.h>
#include <string.h>
#define N 100
int prime[N + 1];
int main(void) {
for (int i = 0; i <= N; i++) prime[i] = 1;
prime[0] = prime[1] = 0;
for (int p = 2; p * p <= N; p++)
if (prime[p])
for (int i = p * p; i <= N; i += p) prime[i] = 0;
for (int i = 2; i <= N; i++) if (prime[i]) printf("%d ", i);
putchar('\n');
return 0;
}
O(n log log n) — 10⁷ পর্যন্ত প্রাইম বের করতে দ্রুত।
5. Modular Exponentiation
#include <stdio.h>
long power_mod(long b, long e, long m) {
long r = 1; b %= m;
while (e > 0) {
if (e & 1) r = r * b % m;
b = b * b % m;
e >>= 1;
}
return r;
}
int main(void) {
printf("2^10 mod 1000 = %ld\n", power_mod(2, 10, 1000));
printf("3^100 mod 1e9+7 = %ld\n", power_mod(3, 100, 1000000007));
return 0;
}
O(log e)। Cryptography, hashing, combinatorics mod p — সবখানে ব্যবহার।
6. Modular Inverse (Fermat's)
// If p prime and gcd(a, p) = 1, Fermat's little: a^(p-1) ≡ 1 (mod p)
// So a^(-1) ≡ a^(p-2) (mod p)
long inv = power_mod(a, p - 2, p);
7. Practice Problems
- Activity selection — max non-overlapping intervals.Activity selection।
✨ Show Answer
Section 2 reference।
- Fractional knapsack.Fractional knapsack।
✨ Show Answer
value/weight ratio-তে desc sort; capacity ভরাট না হওয়া পর্যন্ত item নিন; শেষ item fractional-ভাবে।
- Min number of coins (canonical system).Coin change greedy (canonical)।
✨ Show Answer
Coins desc sort; বড় coin যত সম্ভব নিন তারপর ছোট। USD/BDT-র মতো canonical system-এ কাজ করে; arbitrary-তে DP লাগে।
- Job sequencing with deadlines.Job sequencing।
✨ Show Answer
Profit desc sort; প্রতিটি job-এর জন্য deadline-এর আগের সবচেয়ে late slot নিন (union-find দিয়ে দ্রুত)।
- Minimum platforms needed at a station.Min platforms।
✨ Show Answer
Arrival এবং departure আলাদা sort; two pointers — arrival < dep হলে platform++ (peak track)।
- Huffman coding.Huffman coding।
✨ Show Answer
Min-heap-এ frequency। বারবার দুটি smallest extract → merge → push। Tree-এর left = 0, right = 1।
- Jump game — can reach end?Jump game।
✨ Show Answer
maxReach track করুন; i > maxReach হলে false; maxReach = max(maxReach, i + a[i])।
- Jump game II — min jumps.Jump game II।
✨ Show Answer
BFS-style: current boundary + far tracking। যখন i == boundary, jumps++, boundary = far।
- Gas station circuit.Gas station।
✨ Show Answer
Total ≥ 0 হলে answer আছে। tank negative-এ start = i + 1, tank = 0। O(n)।
- Reorganize string so no two adjacent are equal.String reorganize।
✨ Show Answer
Max-heap-এ frequency। বারবার top 2 নিয়ে একটি করে বসান। Frequency count > (n+1)/2 হলে impossible।
- GCD of array.Array GCD।
✨ Show Answer
gcd(gcd(a[0], a[1]), a[2]) ...— reduce-fold-এর মতো। - LCM of array (modular).Array LCM (modular)।
✨ Show Answer
Overflow এড়াতে
lcm(a, b) = a / gcd(a, b) * b; modular-এ modular inverse লাগে। - Extended Euclid.Extended Euclid।
✨ Show Answer
Section 3-এর
egcd-ই উত্তর। - Linear Diophantine ax + by = c.Diophantine।
✨ Show Answer
gcd(a, b) | c না হলে no solution। নতুবা egcd থেকে (x₀, y₀) বের করে c/g দিয়ে scale করুন।
- Sieve up to 10⁶; list primes.10⁶ পর্যন্ত sieve।
✨ Show Answer
Section 4 reference; শুধু N বদলান।
- Count primes ≤ n.n-এর নিচে prime count।
✨ Show Answer
Sieve চালিয়ে counter বাড়ান — O(n log log n)।
- Smallest prime factor (SPF) of every number up to n.প্রতিটি সংখ্যার SPF।
✨ Show Answer
Sieve-এর modified form:
if (spf[i] == 0) for j in {i, 2i, ...}: if (spf[j] == 0) spf[j] = i;— factorization O(log n)-এ। - Fast exponentiation (iterative).Fast power (iterative)।
✨ Show Answer
Section 5-এর
power_mod-ই iterative version — mod সরিয়ে দিলে সাধারণ power। - a^b mod m for large a, b, m.Big a^b mod m।
✨ Show Answer
Section 5-এর
power_mod-ই উত্তর। a, b, m < 2⁶³ হলেunsigned long longবা__int128ব্যবহার করুন overflow এড়াতে। - nCr mod p for prime p.nCr mod p।
✨ Show Answer
Precompute factorial[] and inv_factorial[] using Fermat's little:
nCr = fact[n] * inv_fact[r] * inv_fact[n-r] % p। - Euler's totient function.Euler's totient।
✨ Show Answer
long phi(long n) { long r = n; for (long p = 2; p * p <= n; p++) if (n % p == 0) { while (n % p == 0) n /= p; r -= r / p; } if (n > 1) r -= r / n; return r; } - Segmented sieve.Segmented sieve।
✨ Show Answer
Range [L, R] (বড়) small prime দিয়ে mark out। Base sieve √R পর্যন্ত; তারপর প্রতিটি prime-এর জন্য [L, R]-এ multiple-গুলো mark।
- Miller-Rabin primality test.Miller-Rabin।
✨ Show Answer
n - 1 = 2^r · d। a^d বের করুন; r-1 বার square করে 1 বা n-1-এ পৌঁছায় কি না চেক। False witness হলে composite।
- Chinese Remainder Theorem.CRT।
✨ Show Answer
Pairwise coprime moduli m₁, m₂, ...-এ x ≡ aᵢ (mod mᵢ)-এর unique solution modulo M = Πmᵢ। Extended Euclid ব্যবহার।
- Pollard's rho factorization (concept).Pollard's rho।
✨ Show Answer
Random walk mod n; cycle-এ gcd factor বের হয়। Miller-Rabin-এর সাথে মিলিয়ে বড় সংখ্যার factorization।
Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| Greedy Algorithm | Make the locally best choice at each step. | প্রতি ধাপে স্থানীয়ভাবে সেরা পছন্দ। |
| Local Optimum | The best choice at one step. | এক ধাপের সেরা পছন্দ। |
| Global Optimum | The overall best solution. | সামগ্রিকভাবে সেরা সমাধান। |
| Exchange Argument | Proof technique that locally swapping does not improve. | স্থানীয় বদল-এ উন্নতি না হওয়ার প্রমাণ-পদ্ধতি। |
| Activity Selection | Classic greedy — pick non-overlapping intervals. | Overlap-হীন interval বাছাই — classic greedy। |
| Huffman Coding | Greedy optimal prefix code. | Greedy optimal prefix কোড। |
| GCD | Greatest Common Divisor. | সর্বোচ্চ সাধারণ গুণনীয়ক। |
| LCM | Least Common Multiple — a*b/gcd(a,b). | সর্বনিম্ন সাধারণ গুণিতক। |
| Euclidean Algorithm | Computes GCD via repeated remainder. | বারবার remainder নিয়ে GCD। |
| Modular Arithmetic | Arithmetic over remainders mod m. | m দিয়ে ভাগ-শেষ-এর গণিত। |
| Prime Number | An integer > 1 with only 1 and itself as divisors. | ১ ও নিজে ছাড়া অন্য কোনো গুণনীয়ক নেই। |
| Sieve of Eratosthenes | O(n log log n) algorithm to list all primes ≤ n. | n পর্যন্ত prime খুঁজে বের করার দ্রুত পদ্ধতি। |
| Modular Exponentiation | Fast a^b mod m in O(log b). | O(log b)-তে a^b mod m। |
| Modular Inverse | The number x such that a·x ≡ 1 (mod m). | a·x ≡ 1 (mod m) পূরণকারী x। |
| Fermat's Little Theorem | If p prime and gcd(a,p)=1, then a^(p-1) ≡ 1 (mod p). | Prime mod-এ inverse বের করার সূত্র। |
Summary — Module 34
Greedy দ্রুত কিন্তু প্রমাণ লাগে। Number theory toolkit: GCD, sieve, modular exponentiation, inverse — competitive programming ও cryptography-র মূল।