šŸ›£ļø Minggu 11: Shortest Paths Algorithms

Bimbingan OSN Informatika - Universitas Bengkulu

Februari 2026
Progress Pembelajaran 0%

šŸŽÆ Pengenalan

Minggu 11 kita mempelajari **Shortest Path Algorithms** - algoritma untuk mencari jalur terpendek dalam graph berbobot (weighted graph)!

šŸ’” Shortest Path dalam Kehidupan Nyata

Shortest Path digunakan dalam:

  • Google Maps: Mencari rute tercepat dari lokasimu ke tujuan
  • GPS Navigation: Menghindari macet, mencari jalur terpendek
  • Network Routing: Internet packets mencari jalur tercepat
  • Flight Planning: Maskapai mencari rute paling efisien

Jenis Shortest Path Problems

Tipe Deskripsi Algoritma
Single-Source Dari satu source ke semua nodes lain Dijkstra, Bellman-Ford
Single-Destination Dari semua nodes ke satu destination Reverse graph + Single-Source
All-Pairs Dari semua nodes ke semua nodes Floyd-Warshall, Johnson's

Tujuan Pembelajaran

Perbandingan Algoritma

Algoritma Time Complexity Negative Edges? Use Case
Dijkstra O((V+E) log V) āŒ Tidak Fastest untuk non-negative
Bellman-Ford O(VE) āœ… Ya Detect negative cycles
Floyd-Warshall O(V³) āœ… Ya All-pairs shortest path

šŸŽÆ Dijkstra's Algorithm

Apa itu Dijkstra?

šŸ“Œ Definisi

Dijkstra's Algorithm adalah algoritma greedy untuk mencari shortest path dari satu source ke semua nodes lain dalam graph dengan non-negative edge weights.

Ide Dasar

1
Inisialisasi

Set distance source = 0, semua node lain = āˆž

2
Priority Queue

Masukkan semua nodes ke priority queue (min-heap)

3
Process Node Terdekat

Ambil node dengan distance terkecil dari PQ

4
Relaxation

Update distance tetangga jika lebih pendek

5
Repeat

Ulangi sampai PQ kosong

Implementasi Dijkstra

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

const int INF = 1e9;
const int MAXN = 100005;

// Adjacency list: adj[u] = {v, weight}
vector<pair<int, int>> adj[MAXN];
int dist[MAXN];

void dijkstra(int start, int N) {
    // Inisialisasi
    for (int i = 1; i <= N; i++) {
        dist[i] = INF;
    }
    dist[start] = 0;
    
    // Priority Queue: {distance, node}
    priority_queue<pair<int, int>, 
                   vector<pair<int, int>>,
                   greater<pair<int, int>>> pq;
    
    pq.push({0, start});
    
    while (!pq.empty()) {
        int u = pq.top().second;
        int d = pq.top().first;
        pq.pop();
        
        // Skip jika sudah ada path lebih pendek
        if (d > dist[u]) continue;
        
        // Relaxation
        for (auto& edge : adj[u]) {
            int v = edge.first;
            int weight = edge.second;
            
            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }
}

int main() {
    int N, M;
    cin >> N >> M;
    
    for (int i = 0; i < M; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
    }
    
    int start;
    cin >> start;
    
    dijkstra(start, N);
    
    // Output shortest distances
    for (int i = 1; i <= N; i++) {
        if (dist[i] == INF) {
            cout << "-1 ";
        } else {
            cout << dist[i] << " ";
        }
    }
    cout << endl;
    
    return 0;
}
šŸ’” Kompleksitas Dijkstra

Time: O((V+E) log V) dengan priority queue
Space: O(V+E)
Catatan: Tidak bekerja dengan negative edges!

Contoh Execution

Graph:
1 --4--> 2
1 --2--> 3
2 --1--> 3
3 --5--> 4

Dijkstra dari node 1:
Initial: dist = [0, INF, INF, INF]
Process 1: dist = [0, 4, 2, INF]
Process 3: dist = [0, 4, 2, 7]
Process 2: dist = [0, 4, 2, 7] (no update)
Process 4: dist = [0, 4, 2, 7]

Result: 0 4 2 7

āš ļø Bellman-Ford Algorithm

Apa itu Bellman-Ford?

šŸ“Œ Definisi

Bellman-Ford Algorithm adalah algoritma untuk mencari shortest path yang dapat menangani negative edge weights dan mendeteksi negative cycles.

Kapan Menggunakan Bellman-Ford?

Implementasi Bellman-Ford

#include <iostream>
#include <vector>
using namespace std;

const int INF = 1e9;

struct Edge {
    int u, v, w;
};

int main() {
    int N, M;
    cin >> N >> M;
    
    vector<Edge> edges(M);
    for (int i = 0; i < M; i++) {
        cin >> edges[i].u >> edges[i].v >> edges[i].w;
    }
    
    // Inisialisasi
    vector<int> dist(N + 1, INF);
    int start;
    cin >> start;
    dist[start] = 0;
    
    // Relax semua edges V-1 kali
    for (int i = 0; i < N - 1; i++) {
        for (auto& edge : edges) {
            if (dist[edge.u] != INF && 
                dist[edge.u] + edge.w < dist[edge.v]) {
                dist[edge.v] = dist[edge.u] + edge.w;
            }
        }
    }
    
    // Cek negative cycle
    bool hasNegativeCycle = false;
    for (auto& edge : edges) {
        if (dist[edge.u] != INF && 
            dist[edge.u] + edge.w < dist[edge.v]) {
            hasNegativeCycle = true;
            break;
        }
    }
    
    if (hasNegativeCycle) {
        cout << "Negative cycle detected!" << endl;
    } else {
        for (int i = 1; i <= N; i++) {
            if (dist[i] == INF) {
                cout << "-1 ";
            } else {
                cout << dist[i] << " ";
            }
        }
        cout << endl;
    }
    
    return 0;
}
šŸ’” Kompleksitas Bellman-Ford

Time: O(VE) - lebih lambat dari Dijkstra
Space: O(V+E)
Keunggulan: Bisa handle negative edges & detect negative cycles!

Negative Cycle

āš ļø Apa itu Negative Cycle?

Negative Cycle adalah cycle dalam graph dimana total weight edge-edge dalam cycle tersebut negatif. Jika ada negative cycle, shortest path tidak terdefinisi (bisa terus berkurang dengan mengulang cycle)!

šŸ”„ Floyd-Warshall Algorithm

Apa itu Floyd-Warshall?

šŸ“Œ Definisi

Floyd-Warshall Algorithm adalah algoritma dynamic programming untuk mencari all-pairs shortest paths (shortest path dari semua nodes ke semua nodes).

Kapan Menggunakan Floyd-Warshall?

Implementasi Floyd-Warshall

#include <iostream>
#include <vector>
using namespace std;

const int INF = 1e9;

int main() {
    int N, M;
    cin >> N >> M;
    
    // Inisialisasi distance matrix
    vector<vector<int>> dist(N + 1, 
                             vector<int>(N + 1, INF));
    
    // Distance ke diri sendiri = 0
    for (int i = 1; i <= N; i++) {
        dist[i][i] = 0;
    }
    
    // Input edges
    for (int i = 0; i < M; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        dist[u][v] = min(dist[u][v], w);  // Handle multiple edges
    }
    
    // Floyd-Warshall Core
    for (int k = 1; k <= N; k++) {        // Intermediate node
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= N; j++) {
                // Relax melalui node k
                dist[i][j] = min(dist[i][j], 
                               dist[i][k] + dist[k][j]);
            }
        }
    }
    
    // Output all-pairs shortest paths
    for (int i = 1; i <= N; i++) {
        for (int j = 1; j <= N; j++) {
            if (dist[i][j] == INF) {
                cout << "-1 ";
            } else {
                cout << dist[i][j] << " ";
            }
        }
        cout << endl;
    }
    
    return 0;
}
šŸ’” Kompleksitas Floyd-Warshall

Time: O(V³) - tiga nested loops
Space: O(V²) - matrix VƗV
Use: All-pairs shortest paths, graph kecil (N ≤ 500)

Perbandingan Ketiga Algoritma

Aspek Dijkstra Bellman-Ford Floyd-Warshall
Type Single-Source Single-Source All-Pairs
Time O((V+E) log V) O(VE) O(V³)
Negative Edges āŒ No āœ… Yes āœ… Yes
Negative Cycle - Detect Detect
Best For Large graph Negative edges All-pairs

šŸ† Soal OSN Relevan

Kumpulan soal OSN-K, OSP, dan OSN Provinsi untuk materi Minggu 11 (Shortest Paths):

šŸ“Œ Keterangan Tingkat Kompetisi
  • OSN-K: Kabupaten/Kota (seleksi pertama)
  • OSP: Provinsi (seleksi kedua)
  • OSN-P: Provinsi (seleksi ketiga)
  • Nasional: OSN tingkat Nasional

A. Dijkstra's Algorithm

Sumber & TahunTopikDeskripsiLevel
OSN-K 2024
Soal No. 30
Dijkstra Shortest path dalam weighted graph ⭐⭐⭐
OSN-K 2023
Soal No. 26
Dijkstra Jarak terpendek dari source ke destination ⭐⭐⭐
OSP 2022
Soal No. 21
Dijkstra Shortest path dengan multiple constraints ⭐⭐⭐⭐

B. Bellman-Ford & Negative Edges

Sumber & TahunTopikDeskripsiLevel
OSN-K 2022
Soal No. 24
Bellman-Ford Graph dengan negative edges ⭐⭐⭐⭐
OSP 2023
Soal No. 19
Negative Cycle Deteksi negative cycle dalam graph ⭐⭐⭐⭐⭐

C. Floyd-Warshall

Sumber & TahunTopikDeskripsiLevel
OSN-K 2024
Soal No. 31
Floyd-Warshall All-pairs shortest paths ⭐⭐⭐⭐
OSN-P 2022
Soal No. 6
Floyd-Warshall Transitive closure & shortest paths ⭐⭐⭐⭐⭐

D. Contoh Soal OSN-K Terbaru

Soal 1: OSN-K 2024 - Shortest Path

Sumber: OSN-K 2024, Soal No. 30

Diberikan weighted graph dengan N nodes dan M edges. Cari shortest path dari node 1 ke node N.

Input
5 6
1 2 4
1 3 2
2 3 1
3 4 5
2 4 3
4 5 2
Output
8

Pembahasan: Path: 1 → 3 → 2 → 4 → 5 = 2 + 1 + 3 + 2 = 8

Soal 2: OSN-K 2024 - All Pairs Shortest Path

Sumber: OSN-K 2024, Soal No. 31

Diberikan graph dengan N nodes. Hitung shortest path untuk semua pairs (i, j).

Input
3 3
1 2 5
2 3 3
1 3 10
Output
0 5 8
5 0 3
8 3 0

Pembahasan: Gunakan Floyd-Warshall untuk all-pairs

E. Link Latihan

šŸŽÆ TLX - Dijkstra šŸ›£ļø TLX - Shortest Path šŸ“Š CSES Graph šŸ’Ŗ Codeforces
šŸ’” Tips Latihan Shortest Path
  • Pemula: Mulai dari Dijkstra basic - ⭐⭐⭐
  • Menengah: Latihan Bellman-Ford - ⭐⭐⭐⭐
  • Lanjut: Coba Floyd-Warshall - ⭐⭐⭐⭐⭐
  • Pahami kapan menggunakan masing-masing algoritma
  • Hati-hati dengan negative edges dan negative cycles!
šŸ“š Referensi Tambahan
  • CP-Algorithms: https://cp-algorithms.com/graph/
  • USACO Guide: https://usaco.guide/gold/shortest-paths
  • Buku TOKI: "Pemrograman Kompetitif Dasar"

āœļø Latihan Soal

Kerjakan soal-soal berikut!

Soal 1: Dijkstra Basic

Implementasikan Dijkstra untuk mencari shortest path dari node 1 ke semua node lain.

Input
4 5
1 2 10
1 3 3
2 3 1
3 2 4
3 4 2
Output
0 7 3 5

Soal 2: Bellman-Ford

Diberikan graph dengan negative edges. Gunakan Bellman-Ford untuk shortest path.

Input
4 5
1 2 6
1 3 7
2 3 8
2 4 5
3 4 -3
Output
0 6 7 4

Soal 3: Floyd-Warshall

Hitung all-pairs shortest paths menggunakan Floyd-Warshall.

Input
3 4
1 2 3
2 1 2
2 3 1
3 1 5
Output
0 3 4
2 0 1
5 8 0

Soal 4: Negative Cycle Detection

Cek apakah graph memiliki negative cycle.

Input
3 3
1 2 1
2 3 -2
3 1 1
Output
YES (ada negative cycle)

Soal 5: Shortest Path dengan Constraints

Cari shortest path dari node 1 ke node N dengan maksimal K edges.

šŸ“Œ Tantangan!

Modifikasi Bellman-Ford untuk limit K edges!

šŸ“ Kuis Pemahaman

Q1. Dijkstra's Algorithm tidak dapat digunakan pada graph dengan...

  • A) Directed edges
  • B) Multiple edges
  • C) Negative edges
  • D) Cycles
āœ… Benar! Dijkstra tidak bekerja dengan negative edges karena greedy choice bisa salah.

Q2. Kompleksitas waktu Dijkstra dengan priority queue adalah...

  • A) O(V²)
  • B) O((V+E) log V)
  • C) O(VE)
  • D) O(V³)
āœ… Benar! Dengan priority queue (min-heap), Dijkstra memiliki kompleksitas O((V+E) log V).

Q3. Algoritma yang dapat mendeteksi negative cycle adalah...

  • A) Bellman-Ford
  • B) Dijkstra
  • C) BFS
  • D) DFS
āœ… Benar! Bellman-Ford dapat mendeteksi negative cycle dengan menjalankan relaxation ke-V kali.

Q4. Floyd-Warshall digunakan untuk...

  • A) Single-source shortest path
  • B) Minimum spanning tree
  • C) Topological sort
  • D) All-pairs shortest path
āœ… Benar! Floyd-Warshall menghitung shortest path dari semua nodes ke semua nodes (all-pairs).

Q5. Kompleksitas Floyd-Warshall adalah...

  • A) O(V+E)
  • B) O(V³)
  • C) O(V² log V)
  • D) O(VE)
āœ… Benar! Floyd-Warshall memiliki tiga nested loops, sehingga O(V³).