/* online_sim.c
 * Reproducible simulations for competitive analysis:
 *  1) Ski Rental: Deterministic vs Karlin optimal vs Uniform vs Old-decreasing vs Learning-Augmented
 *  2) Move-To-Front (MTF) vs Exact DP OPT (4-element walkthrough + 32-element benchmarks)
 *  3) Paging: LRU, FIFO, Randomized Marking, Belady OPT, Yao uniform lower bound, Resource Augmentation
 *  4) 2-Server on a Line: Greedy vs Work Function Algorithm (WFA) vs Exact DP OPT
 *
 * Compile: gcc -O2 -Wall -Wextra -o online_sim online_sim.c -lm
 */
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static uint64_t splitmix64(uint64_t *state) {
    uint64_t z = (*state += 0x9e3779b97f4a7c15ULL);
    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
    z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
    return z ^ (z >> 31);
}

static double rand_unit(uint64_t *rng) {
    return (double)(splitmix64(rng) >> 11) * (1.0 / 9007199254740992.0);
}

static uint64_t rand_range(uint64_t *rng, uint64_t bound) {
    uint64_t limit = UINT64_MAX - (UINT64_MAX % bound);
    uint64_t r;
    do {
        r = splitmix64(rng);
    } while (r >= limit);
    return r % bound;
}

/* ==================== 1. Ski Rental ==================== */

static int ski_cost(int n, int B, int buy_day) {
    if (buy_day > n) return n;
    return (buy_day - 1) + B;
}

static int sample_cdf(const double *probs, int B, uint64_t *rng) {
    double u = rand_unit(rng);
    double acc = 0.0;
    for (int i = 0; i < B; i++) {
        acc += probs[i];
        if (u < acc) return i + 1;
    }
    return B;
}

static void build_karlin_probs(int B, double *probs) {
    double q = 1.0 - 1.0 / (double)B;
    double denom = (double)B * (1.0 - pow(q, (double)B));
    for (int i = 1; i <= B; i++)
        probs[i - 1] = pow(q, (double)(B - i)) / denom;
}

static void build_uniform_probs(int B, double *probs) {
    for (int i = 0; i < B; i++) probs[i] = 1.0 / (double)B;
}

static void build_old_decreasing_probs(int B, double *probs) {
    double q = 1.0 - 1.0 / (double)B;
    double sum = 0.0;
    for (int i = 1; i <= B; i++) {
        probs[i - 1] = pow(q, (double)(i - 1)) / (double)B;
        sum += probs[i - 1];
    }
    for (int i = 0; i < B; i++) probs[i] /= sum;
}

static double exact_expected_ratio(const double *probs, int B, int n) {
    double exp_cost = 0.0;
    for (int i = 1; i <= B; i++)
        exp_cost += probs[i - 1] * (double)ski_cost(n, B, i);
    double opt = (double)(n < B ? n : B);
    return exp_cost / opt;
}

static int psk_learning_augmented_cost(int n, int B, int pred_n, double lam) {
    int buy_day;
    if (pred_n >= B)
        buy_day = (int)ceil(lam * (double)B);
    else
        buy_day = (int)ceil((double)B / lam);
    if (buy_day < 1) buy_day = 1;
    return ski_cost(n, B, buy_day);
}

static void run_ski_rental_exp(void) {
    printf("=== 1. Ski Rental Experiments ===\n");
    int Bs[] = {5, 10, 20, 50, 100};
    uint64_t rng = 20260715ULL;
    double e_ratio = exp(1.0) / (exp(1.0) - 1.0);

    for (int idx = 0; idx < 5; idx++) {
        int B = Bs[idx];
        double p_karlin[128], p_unif[128], p_dec[128];
        build_karlin_probs(B, p_karlin);
        build_uniform_probs(B, p_unif);
        build_old_decreasing_probs(B, p_dec);

        double max_det = 0.0, max_karlin = 0.0, max_unif = 0.0, max_dec = 0.0;
        double mc_karlin_worst = 0.0;
        int trials = 50000;

        for (int n = 1; n <= 3 * B; n++) {
            double opt = (double)(n < B ? n : B);
            double r_det = (double)ski_cost(n, B, B) / opt;
            double r_kar = exact_expected_ratio(p_karlin, B, n);
            double r_uni = exact_expected_ratio(p_unif, B, n);
            double r_dec = exact_expected_ratio(p_dec, B, n);
            if (r_det > max_det) max_det = r_det;
            if (r_kar > max_karlin) max_karlin = r_kar;
            if (r_uni > max_unif) max_unif = r_uni;
            if (r_dec > max_dec) max_dec = r_dec;

            if (B == 10 || B == 20) {
                uint64_t sum = 0;
                for (int t = 0; t < trials; t++) {
                    int bd = sample_cdf(p_karlin, B, &rng);
                    sum += (uint64_t)ski_cost(n, B, bd);
                }
                double mc_r = ((double)sum / trials) / opt;
                if (mc_r > mc_karlin_worst) mc_karlin_worst = mc_r;
            }
        }
        double theory_k = 1.0 / (1.0 - pow(1.0 - 1.0 / B, (double)B));
        printf("B=%3d | Det=%.4f | Karlin exact=%.5f (theory=%.5f, e/(e-1)=%.5f) | Unif=%.4f | OldDec=%.4f",
               B, max_det, max_karlin, theory_k, e_ratio, max_unif, max_dec);
        if (B == 10 || B == 20)
            printf(" | MC_Karlin=%.4f", mc_karlin_worst);
        printf("\n");
    }

    /* Per-n CSV curve for B = 20 */
    {
        int B = 20;
        double p_karlin[128], p_unif[128];
        build_karlin_probs(B, p_karlin);
        build_uniform_probs(B, p_unif);
        printf("\nCSV_SKI_START\n");
        printf("n,opt,det_ratio,karlin_ratio,unif_ratio,psk_acc_ratio,psk_bad_ratio\n");
        for (int n = 1; n <= 40; n++) {
            double opt = (double)(n < B ? n : B);
            double r_det = (double)ski_cost(n, B, B) / opt;
            double r_kar = exact_expected_ratio(p_karlin, B, n);
            double r_uni = exact_expected_ratio(p_unif, B, n);
            double r_acc = (double)psk_learning_augmented_cost(n, B, n, 0.5) / opt;
            int bad_pred = (n < B) ? (2 * B) : 1;
            double r_bad = (double)psk_learning_augmented_cost(n, B, bad_pred, 0.5) / opt;
            printf("%d,%.0f,%.5f,%.5f,%.5f,%.5f,%.5f\n",
                   n, opt, r_det, r_kar, r_uni, r_acc, r_bad);
        }
        printf("CSV_SKI_END\n");
    }

    /* Learning-augmented summary for B=20 across lambda */
    printf("\nLearning-Augmented Ski Rental (B=20, PSK 2018 vs Naive Coin-Flip):\n");
    double lams[] = {0.25, 0.50, 0.80};
    for (int li = 0; li < 3; li++) {
        double lam = lams[li];
        int B = 20;
        double worst_cons = 0.0, worst_rob = 0.0;
        for (int n = 1; n <= 10 * B; n++) {
            double opt = (double)(n < B ? n : B);
            double rc = (double)psk_learning_augmented_cost(n, B, n, lam) / opt;
            if (rc > worst_cons) worst_cons = rc;
            for (int p = 0; p < 2; p++) {
                int pred = (p == 0) ? 1 : 2 * B;
                double rr = (double)psk_learning_augmented_cost(n, B, pred, lam) / opt;
                if (rr > worst_rob) worst_rob = rr;
            }
        }
        double naive_blowup = (lam * (100.0 * B) + (1.0 - lam) * (2.0 * B - 1.0)) / (double)B;
        printf("  lam=%.2f | PSK max_consistency=%.4f (bound %.2f), max_robustness=%.4f (bound %.2f) | Naive mixture at n=100B, pred=1: ratio=%.2f\n",
               lam, worst_cons, 1.0 + lam, worst_rob, 1.0 + 1.0 / lam, naive_blowup);
    }
}

/* ==================== 2. Move-To-Front (MTF) vs Exact OPT ==================== */

static int perms4[24][4];
static int perm_inv_dist[24][24];

static void gen_perms4(void) {
    int p[4] = {0, 1, 2, 3};
    int idx = 0;
    /* Lexicographic permutation generator */
    while (1) {
        memcpy(perms4[idx++], p, sizeof(p));
        int i = 2;
        while (i >= 0 && p[i] >= p[i + 1]) i--;
        if (i < 0) break;
        int j = 3;
        while (p[j] <= p[i]) j--;
        int t = p[i]; p[i] = p[j]; p[j] = t;
        for (int l = i + 1, r = 3; l < r; l++, r--) {
            t = p[l]; p[l] = p[r]; p[r] = t;
        }
    }
    assert(idx == 24);
    for (int a = 0; a < 24; a++) {
        for (int b = 0; b < 24; b++) {
            int pos_b[4];
            for (int i = 0; i < 4; i++) pos_b[perms4[b][i]] = i;
            int inv = 0;
            for (int i = 0; i < 4; i++)
                for (int j = i + 1; j < 4; j++)
                    if (pos_b[perms4[a][i]] > pos_b[perms4[a][j]])
                        inv++;
            perm_inv_dist[a][b] = inv;
        }
    }
}

static int find_perm4(const int *arr) {
    for (int i = 0; i < 24; i++)
        if (memcmp(perms4[i], arr, 4 * sizeof(int)) == 0)
            return i;
    return -1;
}

static void run_mtf_walkthrough(void) {
    gen_perms4();
    const int seq[8] = {3, 2, 1, 0, 3, 2, 1, 0}; /* D, C, B, A, D, C, B, A */
    const char names[4] = {'A', 'B', 'C', 'D'};

    /* Exact DP over all 24 permutations for OPT */
    int dp[9][24], parent[9][24], opt_step_cost[9][24];
    for (int t = 0; t <= 8; t++)
        for (int p = 0; p < 24; p++)
            dp[t][p] = 1000000;
    dp[0][0] = 0; /* perm 0 is [A, B, C, D] */

    for (int t = 0; t < 8; t++) {
        int x = seq[t];
        for (int p = 0; p < 24; p++) {
            if (dp[t][p] >= 1000000) continue;
            int pos = 0;
            while (perms4[p][pos] != x) pos++;
            int access_cost = pos + 1;

            /* Free exchanges allow moving x to any index f in [0..pos] */
            for (int f = 0; f <= pos; f++) {
                int mid[4];
                memcpy(mid, perms4[p], sizeof(mid));
                for (int k = pos; k > f; k--) mid[k] = mid[k - 1];
                mid[f] = x;
                int mid_id = find_perm4(mid);
                for (int q = 0; q < 24; q++) {
                    int paid = perm_inv_dist[mid_id][q];
                    int tot = dp[t][p] + access_cost + paid;
                    if (tot < dp[t + 1][q]) {
                        dp[t + 1][q] = tot;
                        parent[t + 1][q] = p;
                        opt_step_cost[t + 1][q] = access_cost + paid;
                    }
                }
            }
        }
    }

    int best_q = 0;
    for (int q = 1; q < 24; q++)
        if (dp[8][q] < dp[8][best_q]) best_q = q;

    int opt_path[9];
    opt_path[8] = best_q;
    for (int t = 8; t >= 1; t--)
        opt_path[t - 1] = parent[t][opt_path[t]];

    printf("\n=== 2. Move-To-Front (MTF) vs Exact Dynamic OPT (4 items, [D,C,B,A,D,C,B,A]) ===\n");
    int mtf[4] = {0, 1, 2, 3};
    int mtf_total = 0, opt_total = dp[8][best_q];
    int prev_phi = 0;

    for (int t = 0; t < 8; t++) {
        int x = seq[t];
        int pos = 0;
        while (mtf[pos] != x) pos++;
        int c_mtf = pos + 1;
        mtf_total += c_mtf;
        for (int k = pos; k > 0; k--) mtf[k] = mtf[k - 1];
        mtf[0] = x;

        int mtf_id = find_perm4(mtf);
        int phi = perm_inv_dist[mtf_id][opt_path[t + 1]];
        int c_opt = opt_step_cost[t + 1][opt_path[t + 1]];
        int dphi = phi - prev_phi;
        int amort = c_mtf + dphi;
        assert(amort <= 2 * c_opt - 1);

        printf("step %d req=%c | MTF=[%c%c%c%c] c_mtf=%d | OPT=[%c%c%c%c] c_opt=%d | Phi=%d dPhi=%+d amort=%d <= %d\n",
               t + 1, names[x],
               names[mtf[0]], names[mtf[1]], names[mtf[2]], names[mtf[3]], c_mtf,
               names[perms4[opt_path[t + 1]][0]], names[perms4[opt_path[t + 1]][1]],
               names[perms4[opt_path[t + 1]][2]], names[perms4[opt_path[t + 1]][3]], c_opt,
               phi, dphi, amort, 2 * c_opt - 1);
        prev_phi = phi;
    }
    printf("Total: MTF=%d, Exact_OPT=%d, ratio=%.3f\n",
           mtf_total, opt_total, (double)mtf_total / opt_total);

    /* Larger 32-item list update comparison */
    int m = 32, nreq = 8000;
    int list_mtf[32], list_tr[32], list_fc[32], freq[32];
    uint64_t rng = 20260715ULL;
    for (int wl = 0; wl < 2; wl++) {
        for (int i = 0; i < m; i++) {
            list_mtf[i] = list_tr[i] = list_fc[i] = i;
            freq[i] = 0;
        }
        int counts[32] = {0};
        uint64_t cost_mtf = 0, cost_tr = 0, cost_fc = 0;
        for (int t = 0; t < nreq; t++) {
            int req;
            if (wl == 0) {
                req = (m - 1) - (t % m); /* Cyclic reverse */
            } else {
                /* Zipf-like skewed distribution */
                double u = rand_unit(&rng);
                double znorm = 0.0;
                for (int i = 1; i <= m; i++) znorm += 1.0 / pow((double)i, 1.2);
                double acc = 0.0;
                req = m - 1;
                for (int i = 1; i <= m; i++) {
                    acc += (1.0 / pow((double)i, 1.2)) / znorm;
                    if (u <= acc) { req = m - i; break; } /* Hot items start at back! */
                }
            }
            counts[req]++;

            /* MTF */
            int p = 0;
            while (list_mtf[p] != req) p++;
            cost_mtf += (uint64_t)(p + 1);
            for (int k = p; k > 0; k--) list_mtf[k] = list_mtf[k - 1];
            list_mtf[0] = req;

            /* Transpose (free move 1 step forward after access) */
            p = 0;
            while (list_tr[p] != req) p++;
            cost_tr += (uint64_t)(p + 1);
            if (p > 0) {
                int tmp = list_tr[p - 1];
                list_tr[p - 1] = list_tr[p];
                list_tr[p] = tmp;
            }

            /* Frequency Count */
            p = 0;
            while (list_fc[p] != req) p++;
            cost_fc += (uint64_t)(p + 1);
            freq[req]++;
            while (p > 0 && freq[list_fc[p - 1]] < freq[list_fc[p]]) {
                int tmp = list_fc[p - 1];
                list_fc[p - 1] = list_fc[p];
                list_fc[p] = tmp;
                p--;
            }
        }
        /* Static OPT: sort by counts descending */
        int sorted[32];
        memcpy(sorted, counts, sizeof(sorted));
        for (int i = 0; i < m; i++)
            for (int j = i + 1; j < m; j++)
                if (sorted[j] > sorted[i]) {
                    int tmp = sorted[i]; sorted[i] = sorted[j]; sorted[j] = tmp;
                }
        uint64_t cost_static_opt = 0;
        for (int i = 0; i < m; i++) cost_static_opt += (uint64_t)(i + 1) * (uint64_t)sorted[i];

        printf("m=32 %-14s | StaticOPT=%6llu | MTF=%6llu (%.3fx) | Transpose=%6llu (%.3fx) | FreqCount=%6llu (%.3fx)\n",
               wl == 0 ? "Cyclic-Rev" : "Zipf-BackStart",
               (unsigned long long)cost_static_opt,
               (unsigned long long)cost_mtf, (double)cost_mtf / cost_static_opt,
               (unsigned long long)cost_tr, (double)cost_tr / cost_static_opt,
               (unsigned long long)cost_fc, (double)cost_fc / cost_static_opt);
    }

    /* Transpose adversary: alternate between last two items (m-1, m-2) */
    for (int i = 0; i < m; i++)
        list_mtf[i] = list_tr[i] = list_fc[i] = i;
    uint64_t adv_mtf = 0, adv_tr = 0;
    for (int t = 0; t < nreq; t++) {
        int req = (t % 2 == 0) ? (m - 1) : (m - 2);
        int p = 0;
        while (list_mtf[p] != req) p++;
        adv_mtf += (uint64_t)(p + 1);
        for (int k = p; k > 0; k--) list_mtf[k] = list_mtf[k - 1];
        list_mtf[0] = req;

        p = 0;
        while (list_tr[p] != req) p++;
        adv_tr += (uint64_t)(p + 1);
        if (p > 0) {
            int tmp = list_tr[p - 1];
            list_tr[p - 1] = list_tr[p];
            list_tr[p] = tmp;
        }
    }
    uint64_t adv_opt = 2ULL * (uint64_t)nreq; /* Keep {m-1, m-2} at positions 1, 2 */
    printf("m=32 Transpose-Adv  | StaticFront=%6llu | MTF=%6llu (%.3fx) | Transpose=%6llu (%.3fx)\n",
           (unsigned long long)adv_opt,
           (unsigned long long)adv_mtf, (double)adv_mtf / adv_opt,
           (unsigned long long)adv_tr, (double)adv_tr / adv_opt);
}

/* ==================== 3. Paging ==================== */

static int sim_lru(const int *seq, int n, int k) {
    int cache[64], last_used[64], faults = 0, sz = 0;
    for (int t = 0; t < n; t++) {
        int p = seq[t], hit = -1;
        for (int i = 0; i < sz; i++)
            if (cache[i] == p) { hit = i; break; }
        if (hit >= 0) {
            last_used[hit] = t;
        } else {
            faults++;
            if (sz < k) {
                cache[sz] = p;
                last_used[sz] = t;
                sz++;
            } else {
                int vic = 0;
                for (int i = 1; i < k; i++)
                    if (last_used[i] < last_used[vic]) vic = i;
                cache[vic] = p;
                last_used[vic] = t;
            }
        }
    }
    return faults;
}

static int sim_fifo(const int *seq, int n, int k) {
    int cache[64], faults = 0, sz = 0, head = 0;
    for (int t = 0; t < n; t++) {
        int p = seq[t], hit = 0;
        for (int i = 0; i < sz; i++)
            if (cache[i] == p) { hit = 1; break; }
        if (!hit) {
            faults++;
            if (sz < k) {
                cache[sz++] = p;
            } else {
                cache[head] = p;
                head = (head + 1) % k;
            }
        }
    }
    return faults;
}

static int sim_marking(const int *seq, int n, int k, uint64_t *rng) {
    int cache[64], marked[64], faults = 0, sz = 0;
    for (int t = 0; t < n; t++) {
        int p = seq[t], hit = -1;
        for (int i = 0; i < sz; i++)
            if (cache[i] == p) { hit = i; break; }
        if (hit >= 0) {
            marked[hit] = 1;
        } else {
            faults++;
            if (sz < k) {
                cache[sz] = p;
                marked[sz] = 1;
                sz++;
            } else {
                int unm[64], nu = 0;
                for (int i = 0; i < k; i++)
                    if (!marked[i]) unm[nu++] = i;
                if (nu == 0) {
                    for (int i = 0; i < k; i++) marked[i] = 0;
                    for (int i = 0; i < k; i++) unm[i] = i;
                    nu = k;
                }
                int vic = unm[rand_range(rng, (uint64_t)nu)];
                cache[vic] = p;
                marked[vic] = 1;
            }
        }
    }
    return faults;
}

static int sim_belady_opt(const int *seq, int n, int k, int universe) {
    int *next_use = malloc((size_t)n * sizeof(int));
    int *last_pos = malloc((size_t)universe * sizeof(int));
    assert(next_use && last_pos);
    for (int i = 0; i < universe; i++) last_pos[i] = n + 1;
    for (int t = n - 1; t >= 0; t--) {
        next_use[t] = last_pos[seq[t]];
        last_pos[seq[t]] = t;
    }

    int cache[64], cache_next[64], faults = 0, sz = 0;
    for (int t = 0; t < n; t++) {
        int p = seq[t], hit = -1;
        for (int i = 0; i < sz; i++)
            if (cache[i] == p) { hit = i; break; }
        if (hit >= 0) {
            cache_next[hit] = next_use[t];
        } else {
            faults++;
            if (sz < k) {
                cache[sz] = p;
                cache_next[sz] = next_use[t];
                sz++;
            } else {
                int vic = 0;
                for (int i = 1; i < k; i++)
                    if (cache_next[i] > cache_next[vic]) vic = i;
                cache[vic] = p;
                cache_next[vic] = next_use[t];
            }
        }
    }
    free(next_use);
    free(last_pos);
    return faults;
}

static double harmonic(int k) {
    double h = 0.0;
    for (int i = 1; i <= k; i++) h += 1.0 / (double)i;
    return h;
}

static void run_paging_exp(void) {
    printf("\n=== 3. Paging Experiments (Cyclic Adversarial vs Yao Uniform) ===\n");
    int ks[] = {2, 4, 8, 16, 32};
    uint64_t rng = 20260715ULL;

    printf("CSV_PAGING_START\n");
    printf("k,H_k,2H_k,cyc_opt,cyc_lru_ratio,cyc_mark_ratio,yao_opt,yao_lru_ratio,yao_mark_ratio\n");

    for (int ki = 0; ki < 5; ki++) {
        int k = ks[ki];
        int n_cyc = 10000;
        int *cyc = malloc((size_t)n_cyc * sizeof(int));
        assert(cyc);
        for (int t = 0; t < n_cyc; t++) cyc[t] = t % (k + 1);

        int c_opt = sim_belady_opt(cyc, n_cyc, k, k + 1);
        int c_lru = sim_lru(cyc, n_cyc, k);
        int c_fifo = sim_fifo(cyc, n_cyc, k);
        assert(c_lru == c_fifo);
        double c_mark_sum = 0.0;
        int trials = 100;
        for (int tr = 0; tr < trials; tr++)
            c_mark_sum += (double)sim_marking(cyc, n_cyc, k, &rng);
        double c_mark = c_mark_sum / trials;

        int n_yao = 50000;
        int *yao = malloc((size_t)n_yao * sizeof(int));
        assert(yao);
        for (int t = 0; t < n_yao; t++) yao[t] = (int)rand_range(&rng, (uint64_t)(k + 1));

        int y_opt = sim_belady_opt(yao, n_yao, k, k + 1);
        int y_lru = sim_lru(yao, n_yao, k);
        double y_mark_sum = 0.0;
        for (int tr = 0; tr < 40; tr++)
            y_mark_sum += (double)sim_marking(yao, n_yao, k, &rng);
        double y_mark = y_mark_sum / 40.0;

        double hk = harmonic(k);
        printf("%d,%.4f,%.4f,%d,%.4f,%.4f,%d,%.4f,%.4f\n",
               k, hk, 2.0 * hk,
               c_opt, (double)c_lru / c_opt, c_mark / c_opt,
               y_opt, (double)y_lru / y_opt, y_mark / y_opt);

        free(cyc);
        free(yao);
    }
    printf("CSV_PAGING_END\n");

    /* Resource augmentation: LRU(k=16) vs OPT(h) on cyclic k+1=17 */
    printf("\nResource Augmentation (LRU k=16 vs OPT h on cyclic 17-page trace, N=16000):\n");
    int k = 16, n_ra = 16000;
    int *cyc = malloc((size_t)n_ra * sizeof(int));
    assert(cyc);
    for (int t = 0; t < n_ra; t++) cyc[t] = t % (k + 1);
    int lru_k = sim_lru(cyc, n_ra, k);
    int hs[] = {4, 8, 12, 16};
    for (int hi = 0; hi < 4; hi++) {
        int h = hs[hi];
        int opt_h = sim_belady_opt(cyc, n_ra, h, k + 1);
        double bound = (double)k / (double)(k - h + 1);
        printf("  h=%2d: LRU(%d)=%5d, OPT(%2d)=%5d, ratio=%.3f (theory bound k/(k-h+1)=%.3f)\n",
               h, k, lru_k, h, opt_h, (double)lru_k / opt_h, bound);
    }
    free(cyc);
}

/* ==================== 4. 2-Server on a Line (Greedy vs WFA vs DP OPT) ==================== */

typedef struct { int a, b; } Pair;

static int dist_pair(Pair p, Pair q) {
    int d1 = abs(p.a - q.a) + abs(p.b - q.b);
    int d2 = abs(p.a - q.b) + abs(p.b - q.a);
    return d1 < d2 ? d1 : d2;
}

static void run_2server_exp(void) {
    printf("\n=== 4. 2-Server on a Line: Greedy vs WFA vs DP OPT ===\n");
    /* Trace 1: points {0, 1, 10}, start {0, 10}, sequence (1, 0)^25 (50 requests) */
    Pair cfgs[6] = {{0, 0}, {0, 1}, {0, 10}, {1, 1}, {1, 10}, {10, 10}};
    int w[6];
    for (int i = 0; i < 6; i++) w[i] = dist_pair((Pair){0, 10}, cfgs[i]);

    int g_s1 = 0, g_s2 = 10, g_cost = 0;
    int w_s1 = 0, w_s2 = 10, w_cost = 0;

    printf("Step-by-step trace on {0, 1, 10}, init={0,10}, seq=(1,0)^25 (50 requests):\n");
    for (int t = 1; t <= 50; t++) {
        int r = (t % 2 == 1) ? 1 : 0;

        /* Greedy */
        int gd1 = abs(g_s1 - r), gd2 = abs(g_s2 - r);
        if (gd1 <= gd2) { g_cost += gd1; g_s1 = r; }
        else { g_cost += gd2; g_s2 = r; }

        /* Exact Work Function update */
        int w_new[6];
        for (int c = 0; c < 6; c++) {
            int best = 1000000000;
            for (int cp = 0; cp < 6; cp++) {
                if (cfgs[cp].a != r && cfgs[cp].b != r) continue;
                int cand = w[cp] + dist_pair(cfgs[cp], cfgs[c]);
                if (cand < best) best = cand;
            }
            w_new[c] = best;
        }
        memcpy(w, w_new, sizeof(w));

        /* Lazy WFA decision: if already covered, 0 move; else move s1 or s2 to r */
        if (w_s1 != r && w_s2 != r) {
            int move1_cost = abs(w_s1 - r);
            Pair next1 = {r < w_s2 ? r : w_s2, r < w_s2 ? w_s2 : r};
            int move2_cost = abs(w_s2 - r);
            Pair next2 = {r < w_s1 ? r : w_s1, r < w_s1 ? w_s1 : r};

            int idx1 = -1, idx2 = -1;
            for (int c = 0; c < 6; c++) {
                if (cfgs[c].a == next1.a && cfgs[c].b == next1.b) idx1 = c;
                if (cfgs[c].a == next2.a && cfgs[c].b == next2.b) idx2 = c;
            }
            assert(idx1 >= 0 && idx2 >= 0);
            int score1 = w[idx1] + move1_cost;
            int score2 = w[idx2] + move2_cost;

            if (score1 < score2 || (score1 == score2 && move1_cost <= move2_cost)) {
                w_cost += move1_cost;
                w_s1 = r;
            } else {
                w_cost += move2_cost;
                w_s2 = r;
            }
        }

        if (t <= 4 || (t >= 16 && t <= 22) || t == 50) {
            int lo = w_s1 < w_s2 ? w_s1 : w_s2, hi = w_s1 < w_s2 ? w_s2 : w_s1;
            int glo = g_s1 < g_s2 ? g_s1 : g_s2, ghi = g_s1 < g_s2 ? g_s2 : g_s1;
            printf("  t=%2d req=%d | w({0,1})=%2d w({0,10})=%2d w({1,10})=%2d | WFA={%d,%d} cost=%2d | Greedy={%d,%d} cost=%2d\n",
                   t, r, w[1], w[2], w[4], lo, hi, w_cost, glo, ghi, g_cost);
        }
    }
    int opt_cost = w[0];
    for (int i = 1; i < 6; i++)
        if (w[i] < opt_cost) opt_cost = w[i];
    printf("50-step summary: OPT=%d | WFA=%d (ratio=%.3f <= 2k-1=3) | Greedy=%d (ratio=%.3f)\n",
           opt_cost, w_cost, (double)w_cost / opt_cost, g_cost, (double)g_cost / opt_cost);

    /* General random + bursty 2-server test on [0..39] discrete line (40 points -> 820 configs) */
    enum { M = 40, NC = (M * (M + 1)) / 2 };
    Pair all_cfgs[NC];
    int cfg_id[M][M];
    int ncfg = 0;
    for (int a = 0; a < M; a++) {
        for (int b = a; b < M; b++) {
            all_cfgs[ncfg] = (Pair){a, b};
            cfg_id[a][b] = cfg_id[b][a] = ncfg;
            ncfg++;
        }
    }

    uint64_t rng = 20260715ULL;
    for (int mode = 0; mode < 2; mode++) {
        int s1 = 0, s2 = M - 1;
        int gr1 = s1, gr2 = s2, gr_tot = 0;
        int wf1 = s1, wf2 = s2, wf_tot = 0;
        int *wf = malloc((size_t)ncfg * sizeof(int));
        int *wf_next = malloc((size_t)ncfg * sizeof(int));
        assert(wf && wf_next);
        for (int c = 0; c < ncfg; c++)
            wf[c] = dist_pair((Pair){s1, s2}, all_cfgs[c]);

        int len = 300;
        for (int t = 0; t < len; t++) {
            int r;
            if (mode == 0) {
                r = (int)rand_range(&rng, M);
            } else {
                /* Two-cluster bursty requests */
                int phase = (t / 20) % 2;
                r = (phase == 0) ? (int)rand_range(&rng, 4) : (M - 4 + (int)rand_range(&rng, 4));
            }

            /* Greedy */
            int d1 = abs(gr1 - r), d2 = abs(gr2 - r);
            if (d1 <= d2) { gr_tot += d1; gr1 = r; }
            else { gr_tot += d2; gr2 = r; }

            /* Exact WFA update over configs containing r (O(M) per config -> O(M^3)) */
            for (int c = 0; c < ncfg; c++) {
                if (all_cfgs[c].a == r || all_cfgs[c].b == r) {
                    wf_next[c] = wf[c];
                } else {
                    int best = 1000000000;
                    for (int other = 0; other < M; other++) {
                        int cp = cfg_id[r][other];
                        int cand = wf[cp] + dist_pair(all_cfgs[cp], all_cfgs[c]);
                        if (cand < best) best = cand;
                    }
                    wf_next[c] = best;
                }
            }
            memcpy(wf, wf_next, (size_t)ncfg * sizeof(int));

            int c1 = cfg_id[r][wf2], c2 = cfg_id[r][wf1];
            int sc1 = wf[c1] + abs(wf1 - r);
            int sc2 = wf[c2] + abs(wf2 - r);
            if (sc1 < sc2 || (sc1 == sc2 && abs(wf1 - r) <= abs(wf2 - r))) {
                wf_tot += abs(wf1 - r);
                wf1 = r;
            } else {
                wf_tot += abs(wf2 - r);
                wf2 = r;
            }
        }
        int opt = wf[0];
        for (int c = 1; c < ncfg; c++)
            if (wf[c] < opt) opt = wf[c];
        printf("M=%d %-14s | OPT=%4d | WFA=%4d (%.3fx) | Greedy=%4d (%.3fx)\n",
               M, mode == 0 ? "Uniform-300" : "2Cluster-300",
               opt, wf_tot, (double)wf_tot / opt, gr_tot, (double)gr_tot / opt);
        free(wf);
        free(wf_next);
    }
}

int main(void) {
    run_ski_rental_exp();
    run_mtf_walkthrough();
    run_paging_exp();
    run_2server_exp();
    return 0;
}
