jiyuanliu-turing's picture
Publish Rubric-Data dataset
c275678 verified
Raw
History Blame Contribute Delete
448 kB
{"domain": "Machine Learning & Artificial Intelligence", "prompt": "# Hybrid Efficiency Block — Forward Pass Computation\n\nA hybrid efficiency block processes $T = 4$ tokens in a $d = 8$-dimensional embedding space. The input $X \\in \\mathbb{R}^{4 \\times 8}$ is sampled from `numpy.random.RandomState(37).randn(4, 8)`.\n\nThe block integrates four components. The input $X$ is first normalized with RMSNorm producing $x_n$. The normalized $x_n$ feeds **only** the retention branch. The raw input $X$ feeds both the selective state-space branch and the mixture-of-experts branch.\n\n**Numerical conventions:** All computations must be performed in float64 using NumPy semantics. Matrix multiplications follow standard row-by-column rules with explicit broadcasting as defined. Softmax is applied along the last axis unless otherwise noted. The sigmoid function is $\\sigma(x) = 1/(1 + e^{-x})$. All intermediate values must be computed without rounding until the final answers, which are rounded to 4 decimal places.\n\n---\n\n## Component 1: RMSNorm\n\n$$x_n[i, :] = \\frac{X[i, :]}{\\sqrt{\\frac{1}{d}\\sum_{j=1}^{d} X[i,j]^2 + \\varepsilon}} \\quad \\text{where } d = 8,\\; \\varepsilon = 10^{-5}$$\n\nNo mean subtraction. Gain vector is $\\mathbf{1}_8$.\n\n---\n\n## Component 2: Selective State-Space Model (on raw $X$)\n\nA one-dimensional selective scan with continuous parameter $A = -1$. For each token $t = 0, \\ldots, 3$:\n\n1. **Projections:**\n$$B_t = X_t \\cdot W_B \\in \\mathbb{R}^{8}, \\quad C_t = X_t \\cdot W_C \\in \\mathbb{R}^{8}, \\quad \\Delta_t = \\mathrm{softplus}(X_t \\cdot W_\\Delta) \\in \\mathbb{R}$$\nwhere $\\mathrm{softplus}(x) = \\ln(1 + e^x)$ and $W_\\Delta \\in \\mathbb{R}^{8 \\times 1}$ so $\\Delta_t$ is a scalar.\n\n2. **Zero-order hold discretization:**\n$$\\bar{A}_t = e^{\\Delta_t \\cdot A} = e^{-\\Delta_t} \\in \\mathbb{R}, \\quad \\bar{B}_t = (1 - e^{-\\Delta_t}) \\cdot B_t \\in \\mathbb{R}^{8}$$\n\n3. **Recurrence** ($h_0 = \\mathbf{0} \\in \\mathbb{R}^{8}$):\n$$h_t = \\bar{A}_t \\cdot h_{t-1} + \\bar{B}_t \\in \\mathbb{R}^{8}$$\nwhere $\\bar{A}_t$ is a scalar broadcasting across all 8 dimensions.\n\n4. **Output** (element-wise product):\n$$y_{\\text{ssm}}[t] = C_t \\odot h_t \\in \\mathbb{R}^{8}$$\n\n---\n\n## Component 3: Retention Mechanism (on $x_n$)\n\nWith $n_{\\text{heads}} = 2$, $d_{\\text{head}} = 4$, decay $\\gamma = 0.9$.\n\n1. **Projections:**\n$$Q = x_n \\cdot W_{Q_r} \\in \\mathbb{R}^{4 \\times 8}, \\quad K = x_n \\cdot W_{K_r} \\in \\mathbb{R}^{4 \\times 8}, \\quad V = x_n \\cdot W_{V_r} \\in \\mathbb{R}^{4 \\times 8}$$\n\n2. **Reshape** to $Q^{(h)}, K^{(h)}, V^{(h)} \\in \\mathbb{R}^{4 \\times 4}$ for each head $h \\in \\{0, 1\\}$, where head $h$ takes columns $[4h : 4h+4]$.\n\n3. **Causal decay matrix** $D \\in \\mathbb{R}^{4 \\times 4}$:\n$$D_{ij} = \\begin{cases} \\gamma^{i-j} & \\text{if } i \\geq j \\\\ 0 & \\text{otherwise} \\end{cases}$$\n\n4. **Retention scores and output per head:**\n$$S^{(h)} = Q^{(h)} (K^{(h)})^\\top \\in \\mathbb{R}^{4 \\times 4}, \\quad R^{(h)} = (S^{(h)} \\odot D) \\cdot V^{(h)} \\in \\mathbb{R}^{4 \\times 4}$$\n\n5. **Concatenate** heads and project:\n$$y_{\\text{ret}} = [R^{(0)} \\| R^{(1)}] \\cdot W_{O_r} \\in \\mathbb{R}^{4 \\times 8}$$\n\n6. **Retention entropy** $H_{\\text{ret}}$: For each head $h$ and each query position $i$:\n - Compute decay-weighted scores: $z^{(h)}_{ij} = S^{(h)}_{ij} \\cdot D_{ij}$ for $j \\leq i$. Set $z^{(h)}_{ij} = -\\infty$ for $j > i$ (causal mask).\n - Row-normalize via softmax: $W^{(h)}_{ij} = \\frac{\\exp(z^{(h)}_{ij})}{\\sum_{k \\leq i} \\exp(z^{(h)}_{ik})}$\n - Entropy per position: $H^{(h)}_i = -\\sum_{j \\leq i} W^{(h)}_{ij} \\ln W^{(h)}_{ij}$\n - Average: $H_{\\text{ret}} = \\frac{1}{n_{\\text{heads}} \\cdot T} \\sum_{h,i} H^{(h)}_i$ where $T = 4$.\n\n---\n\n## Component 4: Sparse Mixture of Experts (on raw $X$)\n\nWith 2 experts.\n\n1. **Router:** $\\text{logits} = X \\cdot W_{\\text{router}} \\in \\mathbb{R}^{4 \\times 2}$\n2. **Routing probabilities:** $\\text{probs} = \\mathrm{softmax}(\\text{logits}, \\text{axis}=-1) \\in \\mathbb{R}^{4 \\times 2}$\n3. **Top-2 selection:** Since there are exactly 2 experts, both are always selected and weights equal the original softmax probabilities (no renormalization needed).\n4. **Expert outputs and combination:**\n$$y_{\\text{moe}}[t] = \\text{probs}[t, 0] \\cdot (X_t \\cdot W_{e_1}) + \\text{probs}[t, 1] \\cdot (X_t \\cdot W_{e_2}) \\in \\mathbb{R}^{8}$$\n\n---\n\n## Component 5: Linear Attention Fusion\n\n1. **Feature map** $\\phi$ (ELU+1), applied element-wise:\n$$\\phi(x) = \\begin{cases} x + 1 & \\text{if } x \\geq 0 \\\\ e^x & \\text{if } x < 0 \\end{cases}$$\n\n2. **Sources:** Query from $y_{\\text{ret}}$, Key and Value from $y_{\\text{ssm}}$.\n\n3. **Causal linear attention** for each position $i = 0, \\ldots, 3$:\n$$h_{\\text{lin}}[i] = \\frac{\\sum_{j=0}^{i} \\bigl(\\phi(Q_i) \\cdot \\phi(K_j)\\bigr) \\cdot V_j}{\\sum_{j=0}^{i} \\phi(Q_i) \\cdot \\phi(K_j)}$$\nwhere $Q_i = y_{\\text{ret}}[i] \\in \\mathbb{R}^8$, $K_j = y_{\\text{ssm}}[j] \\in \\mathbb{R}^8$, $V_j = y_{\\text{ssm}}[j] \\in \\mathbb{R}^8$, and $\\cdot$ denotes the dot product (scalar). The numerator is a weighted sum of $V_j$ vectors; the denominator is a scalar sum of dot products.\n\n4. **Gated residual:**\n$$h_{\\text{base}} = \\frac{y_{\\text{ssm}} + y_{\\text{ret}} + y_{\\text{moe}}}{3}$$\n$$\\text{gate} = \\sigma(h_{\\text{base}} \\cdot W_r) \\quad \\text{where } \\sigma(x) = \\frac{1}{1 + e^{-x}}$$\n$$h = h_{\\text{base}} + \\text{gate} \\odot h_{\\text{lin}}$$\n\n---\n\n## Component 6: SwiGLU Feed-Forward Network\n\nWith $d_{\\text{ff}} = 12$ and $\\mathrm{Swish}(z) = z \\cdot \\sigma(z) = \\frac{z}{1 + e^{-z}}$.\n\n1. $h_n = \\mathrm{RMSNorm}(h)$ (same formula as Component 1, applied to $h$).\n2. $\\text{gate\\_val} = \\mathrm{Swish}(h_n \\cdot W) \\in \\mathbb{R}^{4 \\times 12}$, $\\quad \\text{linear\\_val} = h_n \\cdot V \\in \\mathbb{R}^{4 \\times 12}$\n3. $\\mathrm{SwiGLU}(h_n) = (\\text{gate\\_val} \\odot \\text{linear\\_val}) \\cdot W_{\\text{down}} \\in \\mathbb{R}^{4 \\times 8}$\n4. Residual: $h_{\\text{final}} = h + \\mathrm{SwiGLU}(h_n) \\in \\mathbb{R}^{4 \\times 8}$\n\n---\n\n## Task Heads\n\n### Classification (Focal Loss)\n- Logits: $\\ell = h_{\\text{final}} \\cdot W_{\\text{cls}} \\in \\mathbb{R}^{4 \\times 4}$\n- Class probabilities: $p = \\mathrm{softmax}(\\ell, \\text{axis}=-1)$\n- Label smoothing ($\\varepsilon = 0.1$, $K = 4$ classes, labels $= [2, 0, 3, 1]$):\n$$y_s[t, k] = \\begin{cases} 1 - \\varepsilon + \\varepsilon/K & \\text{if } k = \\text{label}[t] \\\\ \\varepsilon / K & \\text{otherwise} \\end{cases}$$\n- Per-token cross-entropy: $\\text{CE}[t] = -\\sum_{k} y_s[t,k] \\cdot \\ln p[t,k]$\n- Per-token focal weight using **unsmoothed** true class probability: $p_t = p[t, \\text{label}[t]]$\n- Focal loss: $L_{\\text{cls}} = \\frac{1}{T} \\sum_t (1 - p_t)^\\gamma \\cdot \\text{CE}[t]$ with $\\gamma = 2$\n\n### Regression (Huber Loss)\n- Predictions: $\\hat{y} = h_{\\text{final}} \\cdot W_{\\text{reg}} \\in \\mathbb{R}^{4 \\times 2}$\n- Targets: $y = \\text{RandomState}(71).\\text{randn}(4, 2)$\n- Element-wise error: $e_{ij} = y_{ij} - \\hat{y}_{ij}$\n$$\\text{Huber}(e) = \\begin{cases} \\frac{1}{2} e^2 & \\text{if } |e| \\leq \\delta \\\\ \\delta(|e| - \\frac{1}{2}\\delta) & \\text{otherwise} \\end{cases} \\quad \\text{with } \\delta = 1.0$$\n- $L_{\\text{reg}} = \\frac{1}{4 \\cdot 2} \\sum_{i,j} \\text{Huber}(e_{ij})$\n\n### KL Divergence\n- Token-averaged class distribution: $\\bar{p} = \\frac{1}{T} \\sum_t p[t, :]$\n- $D_{\\text{KL}} = \\sum_{k=1}^{K} \\bar{p}_k \\ln(K \\cdot \\bar{p}_k)$\n\n---\n\n## Total Loss\n\n$$H = H_{\\text{ret}}$$\n$$E = L_{\\text{cls}} + 0.5 \\cdot L_{\\text{reg}} + 0.01 \\cdot H + 0.1 \\cdot D_{\\text{KL}}$$\n\n---\n\n## Weight Initialization\n\nAll 16 weight matrices drawn from a single `RandomState(97)` in the order below, each as `rng.randn(rows, cols) * std`:\n\n| # | Weight | Shape | std | Role |\n|---|--------|-------|-----|------|\n| 1 | $W_B$ | $8 \\times 8$ | $1/\\sqrt{8}$ | SSM B projection |\n| 2 | $W_C$ | $8 \\times 8$ | $1/\\sqrt{8}$ | SSM C projection |\n| 3 | $W_\\Delta$ | $8 \\times 1$ | $1/\\sqrt{8}$ | SSM step size |\n| 4 | $W_{Q_r}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | Retention Q |\n| 5 | $W_{K_r}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | Retention K |\n| 6 | $W_{V_r}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | Retention V |\n| 7 | $W_{O_r}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | Retention output |\n| 8 | $W_{\\text{router}}$ | $8 \\times 2$ | $1/\\sqrt{8}$ | MoE router |\n| 9 | $W_{e_1}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | MoE expert 1 |\n| 10 | $W_{e_2}$ | $8 \\times 8$ | $1/\\sqrt{8}$ | MoE expert 2 |\n| 11 | $W_r$ | $8 \\times 8$ | $1/\\sqrt{8}$ | Gated residual |\n| 12 | $V$ | $8 \\times 12$ | $1/\\sqrt{8}$ | SwiGLU linear |\n| 13 | $W$ | $8 \\times 12$ | $1/\\sqrt{8}$ | SwiGLU gate |\n| 14 | $W_{\\text{down}}$ | $12 \\times 8$ | $1/\\sqrt{12}$ | SwiGLU down |\n| 15 | $W_{\\text{cls}}$ | $8 \\times 4$ | $1/\\sqrt{8}$ | Classification |\n| 16 | $W_{\\text{reg}}$ | $8 \\times 2$ | $1/\\sqrt{8}$ | Regression |\n\nAll biases initialized to zero.\n\n---\n\n## Questions\n\n**Q1:** What is $H$ (retention entropy)? Round to 4 decimal places.\n\n**Q2:** What is $L_{\\text{cls}}$ (focal loss)? Round to 4 decimal places.\n\n**Q3:** What is $L_{\\text{reg}}$ (Huber loss)? Round to 4 decimal places.\n\n**Q4:** What is $D_{\\text{KL}}$? Round to 4 decimal places.\n\n**Q5:** What is $E$ (total loss)? Round to 4 decimal places.", "rubrics": [{"criterion": "Does the answer compute x_n[0,0] = -0.0638 and x_n[1,3] = 1.8106 from the RMSNorm step (values rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer compute y_ssm[0,0] = -0.3166 and y_ssm[2,3] = -0.1890 from the selective SSM recurrence (values rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer compute y_ret[0,0] = -0.3135 and y_ret[2,3] = 1.1332 from the retention mechanism (values rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer report H_ret = 0.2587 (rounded to 4 decimal places)?", "weight": 15}, {"criterion": "Does the answer compute h_final[0,0] = 2.2156 and h_final[2,3] = 0.5309 after the SwiGLU residual (values rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer report L_cls (focal loss) = 2.1703 (rounded to 4 decimal places)?", "weight": 15}, {"criterion": "Does the answer report L_reg (Huber loss) = 1.1017 (rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer report D_KL = 0.1544 and E (total loss) = 2.7392 (rounded to 4 decimal places)?", "weight": 10}, {"criterion": "Does the answer include checksums sum(x_n) = 6.3585, sum(y_ssm) = -0.3665, sum(y_ret) = -0.3220, and sum(h_final) = 13.0751 (rounded to 4 decimal places)?", "weight": 10}], "golden_answer": "## Step 1: RMSNorm\n\nCompute $\\text{RMS}[i] = \\sqrt{\\frac{1}{8}\\sum_j X[i,j]^2 + 10^{-5}}$, then $x_n[i,:] = X[i,:] / \\text{RMS}[i]$.\n\n- Token 0: $\\text{RMS} = 0.85387136$, $x_n[0] = [-0.06378433,\\; 0.78970686,\\; 0.40597102,\\; -1.52288300,\\; 1.77838484,\\; 1.15921877,\\; 0.32520226,\\; -0.52535941]$\n- Token 1: $\\text{RMS} = 0.67845533$, $x_n[1] = [1.41787705,\\; -1.21979827,\\; 0.78805050,\\; 1.81056310,\\; 0.76584605,\\; -0.09338097,\\; -0.05128320,\\; 0.06716072]$\n- Token 2: $\\text{RMS} = 1.17611472$, $x_n[2] = [1.23119379,\\; 1.60996670,\\; 0.34268112,\\; 0.16361166,\\; -0.25821720,\\; -0.73102681,\\; -0.22731360,\\; -1.75930791]$\n- Token 3: $\\text{RMS} = 0.94388047$, $x_n[3] = [-0.75235293,\\; 0.65850531,\\; 1.29411117,\\; -1.81850700,\\; -0.41938624,\\; 1.34950962,\\; -0.01024295,\\; -0.14624853]$\n\nTherefore, $x_n[0,0] = \\mathbf{-0.0638}$ and $x_n[1,3] = \\mathbf{1.8106}$ (rounded to 4 d.p.).\n\nChecksum: $\\text{sum}(x_n) = \\mathbf{6.3585}$ (rounded to 4 d.p.).\n\n---\n\n## Step 2: Selective SSM (on raw $X$)\n\nFor each token: project $B_t = X_t \\cdot W_B$, $C_t = X_t \\cdot W_C$, compute scalar $\\Delta_t = \\mathrm{softplus}(X_t \\cdot W_\\Delta)$, discretize $\\bar{A}_t = e^{-\\Delta_t}$, $\\bar{B}_t = (1 - e^{-\\Delta_t}) \\cdot B_t$, update recurrence $h_t = \\bar{A}_t \\cdot h_{t-1} + \\bar{B}_t$, output $y_{\\text{ssm}}[t] = C_t \\odot h_t$.\n\n**Token 0:**\n- $X_0 \\cdot W_\\Delta = -0.93833015$, $\\Delta_0 = \\mathrm{softplus}(-0.93833015) = \\ln(1 + e^{-0.93833015}) = 0.33022467$\n- $\\bar{A}_0 = e^{-0.33022467} = 0.71876223$, $(1 - \\bar{A}_0) = 0.28123777$\n- $h_0 = \\mathbf{0} \\cdot 0.71876223 + \\bar{B}_0 = \\bar{B}_0$\n- $y_{\\text{ssm}}[0] = [-0.31657334,\\; 0.06090617,\\; -0.23396682,\\; -0.14475338,\\; 0.21397316,\\; 0.05904054,\\; -0.01836393,\\; 0.00552339]$\n\n**Token 1:**\n- $X_1 \\cdot W_\\Delta = 0.41990715$, $\\Delta_1 = 0.92498096$\n- $\\bar{A}_1 = e^{-0.92498096} = 0.39653897$\n- $h_1 = 0.39653897 \\cdot h_0 + \\bar{B}_1$\n- $y_{\\text{ssm}}[1] = [0.01080373,\\; 0.04961334,\\; 0.07608341,\\; -0.03520193,\\; 0.14811167,\\; 0.03234749,\\; -0.51456410,\\; 0.03720833]$\n\n**Token 2:**\n- $X_2 \\cdot W_\\Delta = 0.06514678$, $\\Delta_2 = 0.72625099$\n- $\\bar{A}_2 = e^{-0.72625099} = 0.48371906$\n- $h_2 = 0.48371906 \\cdot h_1 + \\bar{B}_2$\n- $y_{\\text{ssm}}[2] = [-0.03860931,\\; -0.25908878,\\; -0.36513994,\\; -0.18896820,\\; -0.30955984,\\; -0.51076764,\\; 0.35481431,\\; -0.01951336]$\n\n**Token 3:**\n- $X_3 \\cdot W_\\Delta = -1.69920205$, $\\Delta_3 = 0.16790933$\n- $\\bar{A}_3 = e^{-0.16790933} = 0.84543049$\n- $h_3 = 0.84543049 \\cdot h_2 + \\bar{B}_3$\n- $y_{\\text{ssm}}[3] = [-0.12913567,\\; 0.27411209,\\; 0.44832762,\\; 0.16763803,\\; 0.05048704,\\; -0.01371588,\\; 0.82524138,\\; -0.08276301]$\n\nTherefore, $y_{\\text{ssm}}[0,0] = \\mathbf{-0.3166}$ and $y_{\\text{ssm}}[2,3] = \\mathbf{-0.1890}$ (rounded to 4 d.p.).\n\nChecksum: $\\text{sum}(y_{\\text{ssm}}) = \\mathbf{-0.3665}$ (rounded to 4 d.p.).\n\n---\n\n## Step 3: Retention\n\n$Q = x_n \\cdot W_{Q_r}$, $K = x_n \\cdot W_{K_r}$, $V = x_n \\cdot W_{V_r}$. Reshape to 2 heads of $d_{\\text{head}}=4$.\n\nDecay matrix $D$:\n$$D = \\begin{pmatrix} 1.0000 & 0 & 0 & 0 \\\\ 0.9000 & 1.0000 & 0 & 0 \\\\ 0.8100 & 0.9000 & 1.0000 & 0 \\\\ 0.7290 & 0.8100 & 0.9000 & 1.0000 \\end{pmatrix}$$\n\n**Retention entropy per head and position:**\n\nHead 0: $H^{(0)}_0 = 0.00000000$, $H^{(0)}_1 = 0.00186584$, $H^{(0)}_2 = 0.58683032$, $H^{(0)}_3 = 0.95104853$\nHead 1: $H^{(1)}_0 = 0.00000000$, $H^{(1)}_1 = 0.00425098$, $H^{(1)}_2 = 0.15385849$, $H^{(1)}_3 = 0.37143897$\n\nFor Head 0, Position 3 (the largest contributor): $z = [3.01066747,\\; -3.74591348,\\; 1.66717806,\\; 3.24714433]$. After softmax: $W = [0.39543275,\\; 0.00045997,\\; 0.10318168,\\; 0.50092560]$. Entropy $= -\\sum W_j \\ln W_j = 0.95104853$.\n\n$y_{\\text{ret}} = [R^{(0)} \\| R^{(1)}] \\cdot W_{O_r}$\n\nTherefore, $y_{\\text{ret}}[0,0] = \\mathbf{-0.3135}$ and $y_{\\text{ret}}[2,3] = \\mathbf{1.1332}$ (rounded to 4 d.p.).\n\nChecksum: $\\text{sum}(y_{\\text{ret}}) = \\mathbf{-0.3220}$ (rounded to 4 d.p.).\n\n$$H_{\\text{ret}} = \\frac{1}{8}(0.00000000 + 0.00186584 + 0.58683032 + 0.95104853 + 0.00000000 + 0.00425098 + 0.15385849 + 0.37143897) = \\frac{2.06929313}{8} = 0.25866164$$\n\nTherefore, $H_{\\text{ret}} = \\mathbf{0.2587}$ (rounded to 4 d.p.).\n\n---\n\n## Step 4: Mixture of Experts\n\nRouter probabilities (softmax of $X \\cdot W_{\\text{router}}$):\n- Token 0: $[0.45508597,\\; 0.54491403]$\n- Token 1: $[0.73548553,\\; 0.26451447]$\n- Token 2: $[0.85534109,\\; 0.14465891]$\n- Token 3: $[0.35432635,\\; 0.64567365]$\n\n$y_{\\text{moe}}[t] = \\text{probs}[t,0] \\cdot (X_t \\cdot W_{e_1}) + \\text{probs}[t,1] \\cdot (X_t \\cdot W_{e_2})$\n\nTherefore, $y_{\\text{moe}}[0,0] = \\mathbf{0.3095}$ (rounded to 4 d.p.).\n\nChecksum: $\\text{sum}(y_{\\text{moe}}) = \\mathbf{2.4294}$ (rounded to 4 d.p.).\n\n---\n\n## Step 5: Linear Attention Fusion\n\n$h_{\\text{base}} = (y_{\\text{ssm}} + y_{\\text{ret}} + y_{\\text{moe}}) / 3$\n\nTherefore, $h_{\\text{base}}[0,0] = (-0.31657334 + (-0.31349594) + 0.30952753) / 3 = -0.10684725$.\n\nCausal linear attention with $\\phi = \\text{ELU}+1$, Query from $y_{\\text{ret}}$, Key/Value from $y_{\\text{ssm}}$:\n\nFor position 0: only $j=0$ contributes, so $h_{\\text{lin}}[0] = V_0 = y_{\\text{ssm}}[0]$.\n\nTherefore, $h_{\\text{lin}}[0,0] = -0.31657334$.\n\nGated residual: $\\text{gate} = \\sigma(h_{\\text{base}} \\cdot W_r)$, $h = h_{\\text{base}} + \\text{gate} \\odot h_{\\text{lin}}$.\n\nTherefore, $h[0,0] = -0.19915215$.\n\n---\n\n## Step 6: SwiGLU FFN\n\n$h_n = \\text{RMSNorm}(h)$.\n\nTherefore, $h_n[0,0] = -0.41589836$.\n\n$\\text{gate\\_val} = \\text{Swish}(h_n \\cdot W)$, $\\text{linear\\_val} = h_n \\cdot V$, $\\text{SwiGLU} = (\\text{gate\\_val} \\odot \\text{linear\\_val}) \\cdot W_{\\text{down}}$.\n\n$h_{\\text{final}} = h + \\text{SwiGLU}(h_n)$.\n\nTherefore, $h_{\\text{final}}[0,0] = \\mathbf{2.2156}$ and $h_{\\text{final}}[2,3] = \\mathbf{0.5309}$ (rounded to 4 d.p.).\n\nChecksum: $\\text{sum}(h_{\\text{final}}) = \\mathbf{13.0751}$ (rounded to 4 d.p.).\n\n---\n\n## Step 7: Focal Loss\n\nLogits $= h_{\\text{final}} \\cdot W_{\\text{cls}}$, $p = \\text{softmax}(\\text{logits})$.\n\nLabel smoothing: $y_s[t, \\text{label}[t]] = 0.925$, $y_s[t, k \\neq \\text{label}[t]] = 0.025$.\n\n**Token 0** (label=2):\n- $p[0] = [0.16931738,\\; 0.55573335,\\; 0.19369955,\\; 0.08124972]$\n- $p_t = p[0,2] = 0.19369955$\n- $\\text{CE}[0] = -(0.025 \\ln 0.16931738 + 0.025 \\ln 0.55573335 + 0.925 \\ln 0.19369955 + 0.025 \\ln 0.08124972) = 1.64018037$\n- $(1 - 0.19369955)^2 = 0.65012041$\n- Focal contribution: $0.65012041 \\times 1.64018037 = 1.06631474$\n\n**Token 1** (label=0):\n- $p[1] = [0.02615431,\\; 0.06495379,\\; 0.87720469,\\; 0.03168721]$\n- $p_t = 0.02615431$, $\\text{CE} = 3.52838405$, $(1-p_t)^2 = 0.94837543$\n- Focal contribution: $3.34623272$\n\n**Token 2** (label=3):\n- $p[2] = [0.00156533,\\; 0.02789972,\\; 0.86946387,\\; 0.10107108]$\n- $p_t = 0.10107108$, $\\text{CE} = 2.37450335$, $(1-p_t)^2 = 0.80807321$\n- Focal contribution: $1.91877254$\n\n**Token 3** (label=1):\n- $p[3] = [0.73411755,\\; 0.06762737,\\; 0.00147339,\\; 0.19678169]$\n- $p_t = 0.06762737$, $\\text{CE} = 2.70308512$, $(1-p_t)^2 = 0.86931872$\n- Focal contribution: $2.34984249$\n\n$$L_{\\text{cls}} = \\frac{1}{4}(1.06631474 + 3.34623272 + 1.91877254 + 2.34984249) = \\frac{8.68116249}{4} = 2.17029062$$\n\nTherefore, $L_{\\text{cls}} = \\mathbf{2.1703}$ (rounded to 4 d.p.).\n\n---\n\n## Step 8: Huber Loss\n\n$\\hat{y} = h_{\\text{final}} \\cdot W_{\\text{reg}}$, targets $y = \\text{RandomState}(71).\\text{randn}(4,2)$.\n\n| Token | Dim | Prediction | Target | Error | Huber |\n|-------|-----|-----------|--------|-------|-------|\n| 0 | 0 | 0.18738558 | -0.43060315 | -0.61798873 | 0.19095504 |\n| 0 | 1 | -0.67642805 | -1.19392809 | -0.51750004 | 0.13390314 |\n| 1 | 0 | 1.34143401 | -0.44429899 | -1.78573301 | 1.28573301 |\n| 1 | 1 | -0.51755654 | 0.48941221 | 1.00696875 | 0.50696875 |\n| 2 | 0 | 3.25990536 | -0.45155715 | -3.71146251 | 3.21146251 |\n| 2 | 1 | 0.51102252 | 0.58569596 | 0.07467344 | 0.00278806 |\n| 3 | 0 | -2.62122138 | 1.17731982 | 3.79854120 | 3.29854120 |\n| 3 | 1 | -0.35902921 | -0.96500906 | -0.60597984 | 0.18360579 |\n\n$$L_{\\text{reg}} = \\frac{1}{8}(0.19095504 + 0.13390314 + 1.28573301 + 0.50696875 + 3.21146251 + 0.00278806 + 3.29854120 + 0.18360579) = \\frac{8.81395749}{8} = 1.10174469$$\n\nTherefore, $L_{\\text{reg}} = \\mathbf{1.1017}$ (rounded to 4 d.p.).\n\n---\n\n## Step 9: KL Divergence\n\n$\\bar{p} = \\frac{1}{4}\\sum_t p[t,:] = [0.23278864,\\; 0.17905356,\\; 0.48546038,\\; 0.10269742]$\n\n$$D_{\\text{KL}} = \\sum_k \\bar{p}_k \\ln(4 \\cdot \\bar{p}_k) = 0.23278864 \\ln(0.93115457) + 0.17905356 \\ln(0.71621423) + 0.48546038 \\ln(1.94184151) + 0.10269742 \\ln(0.41078970)$$\n$$= -0.01660481 + (-0.05976377) + 0.32216935 + (-0.09136722) = 0.15443355$$\n\nTherefore, $D_{\\text{KL}} = \\mathbf{0.1544}$ (rounded to 4 d.p.).\n\n---\n\n## Step 10: Total Loss\n\n$$E = L_{\\text{cls}} + 0.5 \\cdot L_{\\text{reg}} + 0.01 \\cdot H + 0.1 \\cdot D_{\\text{KL}}$$\n$$= 2.17029062 + 0.55087234 + 0.00258666 + 0.01544335 = 2.73919298$$\n\nTherefore, $E = \\mathbf{2.7392}$ (rounded to 4 d.p.).\n\n---\n\n## Final Answers\n\n- **Q1:** $H = 0.2587$\n- **Q2:** $L_{\\text{cls}} = 2.1703$\n- **Q3:** $L_{\\text{reg}} = 1.1017$\n- **Q4:** $D_{\\text{KL}} = 0.1544$\n- **Q5:** $E = 2.7392$\n\n---\n\n## Verification Code\n\nThe following Python script reproduces all values in this solution. To run it:\n\n```\npython3 -m venv venv\nsource venv/bin/activate # Linux/macOS\nvenv\\Scripts\\activate # Windows\npip install numpy\npython verify.py\n```\n\n```python\nimport numpy as np\n\n# ── INPUT ──\nX = np.random.RandomState(37).randn(4, 8)\n\n# ── WEIGHTS (all drawn from RandomState(97) in order) ──\nrng = np.random.RandomState(97)\n\ndef make_weight(rows, cols, std):\n return rng.randn(rows, cols) * std\n\nW_B = make_weight(8, 8, 1 / np.sqrt(8))\nW_C = make_weight(8, 8, 1 / np.sqrt(8))\nW_Delta = make_weight(8, 1, 1 / np.sqrt(8))\nW_Qr = make_weight(8, 8, 1 / np.sqrt(8))\nW_Kr = make_weight(8, 8, 1 / np.sqrt(8))\nW_Vr = make_weight(8, 8, 1 / np.sqrt(8))\nW_Or = make_weight(8, 8, 1 / np.sqrt(8))\nW_router = make_weight(8, 2, 1 / np.sqrt(8))\nW_e1 = make_weight(8, 8, 1 / np.sqrt(8))\nW_e2 = make_weight(8, 8, 1 / np.sqrt(8))\nW_r = make_weight(8, 8, 1 / np.sqrt(8))\nV_swigl = make_weight(8, 12, 1 / np.sqrt(8))\nW_swigl = make_weight(8, 12, 1 / np.sqrt(8))\nW_down = make_weight(12, 8, 1 / np.sqrt(12))\nW_cls = make_weight(8, 4, 1 / np.sqrt(8))\nW_reg = make_weight(8, 2, 1 / np.sqrt(8))\n\n# ── STEP 1: RMSNorm ──\ndef rmsnorm(X):\n rms = np.sqrt(np.mean(X**2, axis=1, keepdims=True) + 1e-5)\n return X / rms, rms.flatten()\n\nx_n, rms_vals = rmsnorm(X)\n\n# ── STEP 2: Selective SSM ──\ny_ssm = np.zeros((4, 8))\nh_state = np.zeros(8)\nfor t in range(4):\n Bt = X[t] @ W_B\n Ct = X[t] @ W_C\n delta_raw = (X[t] @ W_Delta).item()\n delta_t = np.log(1 + np.exp(delta_raw))\n Abar = np.exp(-delta_t)\n Bbar = (1 - np.exp(-delta_t)) * Bt\n h_state = Abar * h_state + Bbar\n y_ssm[t] = Ct * h_state\n\n# ── STEP 3: Retention ──\nQ = x_n @ W_Qr; K = x_n @ W_Kr; V_ret = x_n @ W_Vr\ngamma = 0.9\nD = np.zeros((4, 4))\nfor i in range(4):\n for j in range(4):\n if i >= j: D[i, j] = gamma ** (i - j)\nn_heads = 2; d_head = 4\nR_all = []; H_ret_total = 0.0\nfor h in range(n_heads):\n Qh = Q[:, h*d_head:(h+1)*d_head]\n Kh = K[:, h*d_head:(h+1)*d_head]\n Vh = V_ret[:, h*d_head:(h+1)*d_head]\n Sh = Qh @ Kh.T\n Rh = (Sh * D) @ Vh\n R_all.append(Rh)\n for i in range(4):\n z = Sh[i, :i+1] * D[i, :i+1]\n z_max = np.max(z)\n z_exp = np.exp(z - z_max)\n W_h = z_exp / np.sum(z_exp)\n ent = -np.sum(W_h * np.log(W_h + 1e-30))\n H_ret_total += ent\nR_concat = np.concatenate(R_all, axis=1)\ny_ret = R_concat @ W_Or\nH_ret = H_ret_total / (n_heads * 4)\n\n# ── STEP 4: MoE ──\ndef softmax(x, axis=-1):\n e = np.exp(x - np.max(x, axis=axis, keepdims=True))\n return e / np.sum(e, axis=axis, keepdims=True)\n\nlogits_moe = X @ W_router; probs_moe = softmax(logits_moe)\ny_moe = np.zeros((4, 8))\nfor t in range(4):\n e1 = X[t] @ W_e1; e2 = X[t] @ W_e2\n y_moe[t] = probs_moe[t, 0] * e1 + probs_moe[t, 1] * e2\n\n# ── STEP 5: Linear Attention Fusion ──\ndef elu_plus1(x):\n return np.where(x >= 0, x + 1, np.exp(x))\n\nh_base = (y_ssm + y_ret + y_moe) / 3.0\nQ_lin = y_ret; K_lin = y_ssm; V_lin = y_ssm\nh_lin = np.zeros((4, 8))\nfor i in range(4):\n phi_Qi = elu_plus1(Q_lin[i])\n num = np.zeros(8); den = 0.0\n for j in range(i + 1):\n phi_Kj = elu_plus1(K_lin[j])\n w = np.dot(phi_Qi, phi_Kj)\n num += w * V_lin[j]; den += w\n h_lin[i] = num / den\ngate = 1.0 / (1.0 + np.exp(-(h_base @ W_r)))\nh = h_base + gate * h_lin\n\n# ── STEP 6: SwiGLU FFN ──\nh_n, _ = rmsnorm(h)\ndef swish(x): return x / (1.0 + np.exp(-x))\ngate_val = swish(h_n @ W_swigl)\nlinear_val = h_n @ V_swigl\nswiglu_out = (gate_val * linear_val) @ W_down\nh_final = h + swiglu_out\n\n# ── STEP 7: Focal Loss ──\nlogits_cls = h_final @ W_cls; p = softmax(logits_cls)\nlabels = [2, 0, 3, 1]; eps = 0.1; K_cls = 4; gamma_focal = 2\nL_cls = 0.0\nfor t in range(4):\n ys = np.full(K_cls, eps / K_cls)\n ys[labels[t]] = 1 - eps + eps / K_cls\n ce = -np.sum(ys * np.log(p[t]))\n pt = p[t, labels[t]]\n focal_w = (1 - pt) ** gamma_focal\n L_cls += focal_w * ce\nL_cls /= 4\n\n# ── STEP 8: Huber Loss ──\ny_pred = h_final @ W_reg\ny_target = np.random.RandomState(71).randn(4, 2)\ne = y_target - y_pred; delta_h = 1.0\nhuber_total = 0.0\nfor i in range(4):\n for j in range(2):\n ae = abs(e[i, j])\n if ae <= delta_h: hub = 0.5 * e[i, j]**2\n else: hub = delta_h * (ae - 0.5 * delta_h)\n huber_total += hub\nL_reg = huber_total / 8\n\n# ── STEP 9: KL Divergence ──\np_bar = np.mean(p, axis=0)\nD_KL = np.sum(p_bar * np.log(K_cls * p_bar))\n\n# ── STEP 10: Total Loss ──\nE = L_cls + 0.5 * L_reg + 0.01 * H_ret + 0.1 * D_KL\n\n# ── PRINT ALL CHECKPOINTS ──\nprint(f\"x_n[0,0] = {round(x_n[0,0], 4)}\")\nprint(f\"x_n[1,3] = {round(x_n[1,3], 4)}\")\nprint(f\"sum(x_n) = {round(np.sum(x_n), 4)}\")\nprint(f\"y_ssm[0,0] = {round(y_ssm[0,0], 4)}\")\nprint(f\"y_ssm[2,3] = {round(y_ssm[2,3], 4)}\")\nprint(f\"sum(y_ssm) = {round(np.sum(y_ssm), 4)}\")\nprint(f\"y_ret[0,0] = {round(y_ret[0,0], 4)}\")\nprint(f\"y_ret[2,3] = {round(y_ret[2,3], 4)}\")\nprint(f\"sum(y_ret) = {round(np.sum(y_ret), 4)}\")\nprint(f\"H_ret = {round(H_ret, 4)}\")\nprint(f\"y_moe[0,0] = {round(y_moe[0,0], 4)}\")\nprint(f\"sum(y_moe) = {round(np.sum(y_moe), 4)}\")\nprint(f\"h_final[0,0] = {round(h_final[0,0], 4)}\")\nprint(f\"h_final[2,3] = {round(h_final[2,3], 4)}\")\nprint(f\"sum(h_final) = {round(np.sum(h_final), 4)}\")\nprint(f\"L_cls = {round(L_cls, 4)}\")\nprint(f\"L_reg = {round(L_reg, 4)}\")\nprint(f\"D_KL = {round(D_KL, 4)}\")\nprint(f\"E = {round(E, 4)}\")\n```"}
{"domain": "Computer Systems & Operating Systems", "prompt": "# Distributed Operating Systems - Coordinated Execution Analysis (Deterministic Trace, Derived-Constants Spec)\n\n## 0) Reading rules (AUTHORITATIVE)\n\nThis document contains:\n- AUTHORITATIVE rules (must be followed)\n- LEGACY notes (included for realism; must be ignored if they conflict)\n\nIf any statement conflicts, AUTHORITATIVE wins.\n\nYou must reconstruct a deterministic execution trace over:\n- t in [0,50)\n\nAll outputs must be derived only from this prompt. No unstated behaviors are allowed.\n\n## 1) Canonical constants (AUTHORITATIVE)\n\nLet:\n- Q = 10 (ms) (the time quantum)\n- HALFQ = Q/2 = 5 (ms)\n- ONE = 1 (ms)\n- TWO = 2 (ms)\n\nAll times in this task are integers in milliseconds.\n\nDefine these derived timestamps (all computed from Q, HALFQ, ONE, TWO):\n- t_P3_spawn = Q + TWO\n- t_gc_read = 2*Q + (Q - TWO) (note: Q - TWO = 8)\n- t_pf_start = t_gc_read\n- t_pf_end = t_pf_start + Q\n- t_timeout = 4*Q + (HALFQ) (note: HALFQ=5)\n- t_sleep_end = t_timeout + ONE\n- t_cleanup_end = t_sleep_end + TWO\n\nDefine the three P1 store times for V:\n- t_V1 = Q\n- t_V2 = 2*Q\n- t_V3 = 3*Q\n\nDefine the 2PC phase boundaries:\n- t_prepare_send = 0\n- t_commit_send = t_V3\n\n## 2) Time ordering (AUTHORITATIVE)\n\nIf multiple events occur at the same timestamp t, process them in this exact order:\n1) Network deliveries scheduled at time t\n2) Unblocks whose unblock-time is exactly t\n3) Scheduler decisions at time t (preemption/dispatch)\n4) CPU-defined memory operations specified to occur exactly at time t\n\nSnapshots at time t must be taken after steps (1)-(4).\n\nCross-node linearization for CPU-defined memory operations at the same timestamp t:\n- Node A operations happen first, then Node B, then Node C\nAll coherence reactions complete immediately before the next linearized operation.\n\nLEGACY note (ignore): \"Snapshots are taken before CPU ops.\" (This LEGACY note is false for this task.)\n\n## 3) Scheduler (AUTHORITATIVE)\n\n- Preemptive fixed priority scheduling: higher numeric priority preempts immediately.\n- Exact quantum: Q ms per dispatch.\n- If a process blocks or is preempted, remaining quantum is discarded.\n- If a process continues past a quantum boundary while still running, treat it as a fresh dispatch with a new Q ms quantum.\n- Context switch cost is 0ms.\n- Message handling cost is 0ms and does not consume user CPU time.\n\n## 4) Shared mapped page F (AUTHORITATIVE)\n\nThere is exactly one scored shared memory-mapped page F with two 32-bit words:\n- L on cache line CL_L (lock word)\n- V on cache line CL_V (data word)\n\nInitial state at t=0-:\n- L = 0\n- V = 0\n- MESI states:\n - CL_L: A=S, B=S, C=S\n - CL_V: A=S, B=S, C=S\n\nOnly CL_L and CL_V are scored for MESI output.\n\n## 5) Lock semantics on L (AUTHORITATIVE)\n\nEncoding:\n- L = 0 unlocked\n- L = 1 writer lock held by P1\n- L = 2 writer lock held by P2\n\nWriter preference:\n- If any writer is waiting (spinning), all reader acquisitions fail until a writer acquires and releases.\n\nDeterministic spin algorithm (runs only while scheduled):\n- At each integer ms boundary while scheduled, a waiting process performs exactly one non-temporal load of L.\n- Non-temporal loads do not allocate CL_L and do not change the local MESI state of CL_L.\n- A writer performs CAS(L,0,writer_id) only if its immediately preceding non-temporal load observed L==0.\n- A reader acquires only if its load observed L==0 AND there are no waiting writers.\n\nLEGACY note (ignore): \"Spin loads allocate cache lines like normal reads.\" (This LEGACY note is false for this task.)\n\n## 6) Processes and priorities (AUTHORITATIVE)\n\n### Node A\n- P1 priority = 2, runnable at t=0, only user process on Node A.\n- At t=0, P1 acquires writer lock via cached store L := 1.\n\nP1 performs three updates while holding the lock:\n- U1 compute over [0,t_V1), then at t_V1 do cached store V := V + 1\n- U2 compute over [t_V1,t_V2), then at t_V2 do cached store V := V + 1\n- U3 compute over [t_V2,t_V3), then at t_V3 do cached store V := V + 1\n\n2PC coordinator actions:\n- At t_prepare_send, send PREPARE_RESERVE(T).\n- At t_commit_send, after the V store, send COMMIT(T,V_final) and then block waiting for ACKs.\n\nBlocking semantics on Node A:\n- When P1 blocks, it is not runnable and consumes 0 CPU.\n- If no other runnable processes exist (true here), CPU is idle.\n- In CPU traces, BLK means \"P1 blocked and CPU idle\".\n\nLock release actions at the unique release time t_release (defined by the 2PC release rule below):\nAt timestamp t_release, Node A performs in this order:\n1) explicit write-back of CL_V and downgrade CL_V M->E if no sharers exist at that instant\n2) cached store L := 0 (unlock)\n\nAfter releasing, P1 runs CPU-only cleanup over [t_release,50).\n\n### Node B\n- P2 priority = 2, runnable at t=0; spins for writer lock when scheduled; never blocks in [0,50).\n- P3 priority = 3, becomes runnable at t_P3_spawn.\n - From t_P3_spawn until t_timeout, attempts read lock (always fails in this run).\n - At t_pf_start while running, touches metadata and blocks due to a page fault for [t_pf_start,t_pf_end).\n - At t_timeout, calls sleep(ONE), blocking [t_timeout,t_sleep_end).\n - Over [t_sleep_end,t_cleanup_end), runs CPU-only cleanup for exactly TWO ms, then blocks [t_cleanup_end,50).\n\nDeterministic post-release access:\n- At timestamp t_release, after Node A has executed the unlock store L:=0 in the cross-node linearization, P2 performs a successful acquisition CAS and then cached store L := 2 at timestamp t_release.\n- At timestamp (t_release + ONE), P2 performs exactly one cached read PrRd(V) and performs no writes to V in [t_release,50).\n\n### Node C\n- GC priority = 1, runnable at t=0, runs continuously over [0,4*Q).\n- At t_gc_read exactly, GC performs one cached read PrRd(V).\n- Node C is idle over [4*Q,50). Use IDLE in traces.\n\n## 7) 2PC protocol constants (AUTHORITATIVE)\n\nCoordinator: Node A (P1)\nParticipants: Node B, Node C\n\nNetwork bounds: one-way latency is within [5,15] ms.\nFor this deterministic run, latencies are defined from Q and HALFQ:\n\n- PREPARE_RESERVE latency A->B = Q, and A->C = Q\n- VOTE_YES latency B->A = Q, and C->A = Q\n- COMMIT latency A->B = HALFQ, and A->C = HALFQ\n- ACK_COMMIT latency B->A = Q, and C->A = HALFQ\n\nPrepare phase:\n- t_prepare_send: A sends PREPARE_RESERVE(T)\n- t_prepare_send + Q: B and C receive PREPARE, log prepared instantly, send VOTE_YES(T)\n- t_prepare_send + 2*Q: A receives both VOTE_YES(T)\n\nCommit phase:\n- t_commit_send: A sends COMMIT(T,V_final)\n- t_commit_send + HALFQ: B and C receive COMMIT\n- On receipt of COMMIT, each participant must touch its commit-log page before sending ACK_COMMIT.\n- Node B commit-log page fault rule: Node B cannot touch its commit-log page during [t_pf_start,t_pf_end). If COMMIT arrives during that interval, B delays its ACK until t_pf_end.\n- Node C has no delay.\n\nCoordinator release rule (defines t_release uniquely):\n- P1 releases the writer lock only after receiving ACK_COMMIT from both B and C.\n\n## 8) MESI-like coherence model (AUTHORITATIVE)\n\nStates: M, E, S, I.\n\n- Cached store: writer obtains ownership, ends in M, invalidates other nodes to I.\n- Cached read PrRd on I: requester becomes S.\n- If another node holds M and a cached read occurs elsewhere: owner flushes and downgrades M->S, requester becomes S.\n- At t_release, Node A explicitly write-backs CL_V and downgrades M->E if no other sharers exist at that instant.\n- At t_release + ONE, Node B cached reads V once, causing A: E->S and B: I->S for CL_V.\n- Non-temporal spin loads of L do not allocate CL_L and do not change CL_L MESI states.\n\n## 9) Tasks\n\nCompute deterministic outputs for t in [0,50):\n\n1) Timeline for exactly these 12 intervals:\n [0,10), [10,12), [12,20), [20,28), [28,30), [30,35), [35,38), [38,40), [40,45), [45,46), [46,48), [48,50)\n\n2) Identify deadlock, livelock, and priority inversion points using explicit times.\n\n3) Final state:\n- final L and V at t=50-\n- MESI snapshots for CL_L and CL_V for all nodes at t = 0, 10, 35, 48, 50\n- mention the transient coherence event at t=28 caused by GC's cached read of V\n\n4) Numeric performance:\n- throughput = committed updates per second over the 50ms window\n- lock utilization efficiency:\n \\[\n \\text{efficiency} = \\frac{\\text{productive lock time}}{\\text{lock held time}}\n \\]\n productive lock time is 30ms, lock held time is from t=0 to t_release\n\n## 10) Required Output Lines (Keys and Formats)\n\nYour final answer must include these keys exactly once each, using these formats:\n\nSNAPSHOT_TIMES_MS = [0,10,35,48,50]\n\nINTERVALS = [[0,10),[10,12),[12,20),[20,28),[28,30),[30,35),[35,38),[38,40),[40,45),[45,46),[46,48),[48,50)]\n\nCPU_TRACES = [A:[x1,...,x12],B:[y1,...,y12],C:[z1,...,z12]]\n- Each xi, yi, zi is one of: P1, P2, P3, GC, BLK, IDLE\n\nV_FINAL = <integer>\nL_FINAL = <integer>\n\nMESI_CL_V_ALL = [A:[s0,s10,s35,s48,s50],B:[t0,t10,t35,t48,t50],C:[u0,u10,u35,u48,u50],T28:A:p->q,C:r->w]\n\nMESI_CL_L_ALL = [A:[a0,a10,a35,a48,a50],B:[b0,b10,b35,b48,b50],C:[c0,c10,c35,c48,c50]]\n\nTHROUGHPUT_UPDATES_PER_SEC = <integer>\nLOCK_EFFICIENCY_PERCENT = <decimal>\n\nPRIORITY_INVERSION_DURATION_MS = <integer>\nLIVELOCK_PRESENT = <YES/NO>\nDEADLOCK_POSSIBLE_2PC_BLOCKING = <YES/NO>", "rubrics": [{"criterion": "Does the answer contain the exact line 'SNAPSHOT_TIMES_MS = [0,10,35,48,50]'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'INTERVALS = [[0,10),[10,12),[12,20),[20,28),[28,30),[30,35),[35,38),[38,40),[40,45),[45,46),[46,48),[48,50)]'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'CPU_TRACES = [A:[P1,P1,P1,P1,P1,BLK,BLK,BLK,BLK,BLK,BLK,P1],B:[P2,P2,P3,P3,P2,P2,P2,P3,P3,P2,P3,P2],C:[GC,GC,GC,GC,GC,GC,GC,GC,IDLE,IDLE,IDLE,IDLE]]'?", "weight": 15}, {"criterion": "Does the answer contain the exact line 'V_FINAL = 3'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'L_FINAL = 2'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'MESI_CL_V_ALL = [A:[S,M,M,E,S],B:[S,I,I,I,S],C:[S,I,I,I,I],T28:A:M->S,C:I->S]'?", "weight": 15}, {"criterion": "Does the answer contain the exact line 'MESI_CL_L_ALL = [A:[M,M,M,I,I],B:[I,I,I,M,M],C:[I,I,I,I,I]]'?", "weight": 10}, {"criterion": "Does the answer contain the exact line 'THROUGHPUT_UPDATES_PER_SEC = 60'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'LOCK_EFFICIENCY_PERCENT = 62.5'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'PRIORITY_INVERSION_DURATION_MS = 33'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'LIVELOCK_PRESENT = YES'?", "weight": 5}, {"criterion": "Does the answer contain the exact line 'DEADLOCK_POSSIBLE_2PC_BLOCKING = YES'?", "weight": 5}, {"criterion": "Does the answer explicitly state that t_release = 48 derived from receiving both ACK_COMMIT messages after the Node B delay due to the page fault interval [28,38)?", "weight": 10}, {"criterion": "Does the answer correctly explain the transient MESI event at t=28 where GC's cached read forces A: M->S and C: I->S for CL_V?", "weight": 10}, {"criterion": "Does the answer correctly reflect that Node B's ACK is delayed until t_pf_end = 38 due to the page fault interval, leading to final ACK arrival at t=48?", "weight": 5}], "golden_answer": "## 1) Compute derived timestamps from Q=10 and HALFQ=5\n\nQ=10, HALFQ=5, ONE=1, TWO=2\n\nt_P3_spawn = Q + TWO = 12\nt_gc_read = 2*Q + (Q - TWO) = 20 + 8 = 28\nt_pf_start = 28\nt_pf_end = t_pf_start + Q = 28 + 10 = 38\nt_timeout = 4*Q + HALFQ = 40 + 5 = 45\nt_sleep_end = t_timeout + ONE = 46\nt_cleanup_end = t_sleep_end + TWO = 48\n\nt_V1 = Q = 10\nt_V2 = 2*Q = 20\nt_V3 = 3*Q = 30\n\n## 2) Determine t_release from 2PC rules\n\nPrepare:\n- t_prepare_send=0\n- PREPARE arrives at 0+Q=10\n- VOTE_YES arrives at 0+2Q=20\n\nCommit:\n- t_commit_send = t_V3 = 30\n- COMMIT arrives at 30+HALFQ = 35\n\nACKs:\n- Node C ACK latency is HALFQ, and Node C has no log delay:\n - C sends ACK at 35, A receives at 35+HALFQ = 40\n- Node B cannot touch commit log during [t_pf_start,t_pf_end) = [28,38)\n - COMMIT arrives at 35 within [28,38), so B delays sending ACK until 38\n - B->A ACK latency is Q, so A receives B ACK at 38+Q = 48\n\nCoordinator releases only after both ACKs received, so:\nt_release = 48\n\n## 3) Timeline (t in [0,50))\n\n| Interval | Node A | Node B | Node C |\n|---|---|---|---|\n| [0,10) | P1 | P2 | GC |\n| [10,12) | P1 | P2 | GC |\n| [12,20) | P1 | P3 | GC |\n| [20,28) | P1 | P3 | GC |\n| [28,30) | P1 | P2 | GC |\n| [30,35) | BLK | P2 | GC |\n| [35,38) | BLK | P2 | GC |\n| [38,40) | BLK | P3 | GC |\n| [40,45) | BLK | P3 | IDLE |\n| [45,46) | BLK | P2 | IDLE |\n| [46,48) | BLK | P3 | IDLE |\n| [48,50) | P1 | P2 | IDLE |\n\n## 4) Deadlock, Livelock, Priority Inversion\n\nPriority inversion:\n- P3 attempts from t=12 until t=45 but cannot acquire while P1 holds writer lock until t=48 and writer preference blocks readers while writer P2 is waiting.\n- Duration = 45 - 12 = 33ms.\n\nLivelock:\n- P2 and P3 repeatedly retry lock acquisition while L remains nonzero until t=48, consuming CPU without acquisition progress until release.\n\nDeadlock possible (2PC blocking):\n- 2PC is a blocking protocol if the coordinator fails after participants have voted YES; in this run there is no failure but blocking risk exists by protocol structure.\n\n## 5) Final values and MESI snapshots\n\nFinal values at t=50-:\n- V_FINAL = 3\n- L_FINAL = 2\n\nCL_V transient at t=28:\n- At t=28, A holds CL_V in M (from store at t=20).\n- GC cached PrRd(V) forces A: M->S and C: I->S.\n- At t=30, P1 stores V:=3, forcing A: S->M and C: S->I.\n\nCL_V snapshots at t = 0,10,35,48,50:\n- t=0: A=S, B=S, C=S\n- t=10: A=M, B=I, C=I\n- t=35: A=M, B=I, C=I\n- t=48: A=E, B=I, C=I\n- t=50: A=S, B=S, C=I\n\nCL_L snapshots at t = 0,10,35,48,50:\n- t=0: A=M, B=I, C=I\n- t=10: A=M, B=I, C=I\n- t=35: A=M, B=I, C=I\n- t=48: A=I, B=M, C=I\n- t=50: A=I, B=M, C=I\n\n## 6) Performance\n\nThroughput:\n- 3 committed updates over 50ms = 0.050s\n- Throughput = 3 / 0.050 = 60 updates/s\n\nLock utilization efficiency:\n- Productive lock time = 30ms\n- Lock held time = t_release - 0 = 48ms\n\\[\n\\text{efficiency} = \\frac{30}{48} = 0.625 = 62.5\n\\]\n\n## 7) Required Output Lines\n\nSNAPSHOT_TIMES_MS = [0,10,35,48,50]\n\nINTERVALS = [[0,10),[10,12),[12,20),[20,28),[28,30),[30,35),[35,38),[38,40),[40,45),[45,46),[46,48),[48,50)]\n\nCPU_TRACES = [A:[P1,P1,P1,P1,P1,BLK,BLK,BLK,BLK,BLK,BLK,P1],B:[P2,P2,P3,P3,P2,P2,P2,P3,P3,P2,P3,P2],C:[GC,GC,GC,GC,GC,GC,GC,GC,IDLE,IDLE,IDLE,IDLE]]\n\nV_FINAL = 3\nL_FINAL = 2\n\nMESI_CL_V_ALL = [A:[S,M,M,E,S],B:[S,I,I,I,S],C:[S,I,I,I,I],T28:A:M->S,C:I->S]\n\nMESI_CL_L_ALL = [A:[M,M,M,I,I],B:[I,I,I,M,M],C:[I,I,I,I,I]]\n\nTHROUGHPUT_UPDATES_PER_SEC = 60\nLOCK_EFFICIENCY_PERCENT = 62.5\n\nPRIORITY_INVERSION_DURATION_MS = 33\nLIVELOCK_PRESENT = YES\nDEADLOCK_POSSIBLE_2PC_BLOCKING = YES"}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem\n\nYou are given an `n × m` grid (`1 ≤ n,m ≤ 200`) filled with digits `0..9`.\n\nFor each digit `d` (`0..9`), you are also given a move vector `(a[d], b[d])` (each component in `[-200,200]`).\n\nDefine Wilbur’s movement rule:\n\n- If Wilbur is currently at cell `(x,y)` and the digit there is `d`, then his **forced next position** is `(x + a[d], y + b[d])` **if** that cell is inside the grid.\n- If the forced next position is outside the grid, Wilbur **stays** at `(x,y)`.\n\nBefore each forced move, Wilbur may either:\n- append the current cell’s digit to a whiteboard string, or\n- append nothing.\n\nDigits appended over time form a string (appended to the end each time).\n\nYou are given `q` query strings `s1..sq` (digits only). For each query `s`, determine whether there exists **some starting cell** such that, after finitely many forced moves (and optional writes), Wilbur can obtain **exactly** the string `s` on the whiteboard.\n\n### Input\n- `n m q` (`1..200`)\n- `n` lines of `m` digits each (the grid)\n- 10 lines: for digit `d`, line contains `a[d] b[d]`\n- `q` lines: the query strings (total length over all queries ≤ `1,000,000`)\n\n### Output\nFor each query, print `YES` if possible, else `NO`.\n", "rubrics": [{"criterion": "The answer models the forced movement as a directed graph on the grid cells in which every vertex has outdegree exactly 1.", "weight": 10}, {"criterion": "The answer states that when the forced next position is outside the grid, the transition is a self-loop (the cell transitions to itself).", "weight": 10}, {"criterion": "The answer states that any writable whiteboard string is a subsequence of the digit sequence along the forced walk from a chosen start cell.", "weight": 10}, {"criterion": "The answer states that each (weakly) connected component of a functional graph contains exactly one directed cycle.", "weight": 10}, {"criterion": "The answer defines the reverse adjacency relation in the form rev[u] = { v : to[v] = u}?", "weight": 10}, {"criterion": "The answer states that the query string is reversed (r = reverse(s)) for the main search procedure.", "weight": 10}, {"criterion": "The answer defines a per-query transition nxt(pos, d) that advances the matched position by 1 exactly when r[pos] equals digit d.", "weight": 10}, {"criterion": "The answer defines bestPos[v] as the maximum matched-prefix length reached so far at vertex v.", "weight": 10}, {"criterion": "The answer includes a dominance pruning rule that discards a visit to vertex v when the new matched length is less than or equal to bestPos[v].", "weight": 10}, {"criterion": "The answer includes an explicit acceptance condition that outputs YES when the matched length reaches L.", "weight": 10}], "golden_answer": "### 1) Build the functional graph of forced moves\n\nIndex each cell `(x,y)` as a vertex `v` (total `V = n*m ≤ 40000`). \nLet `dig[v]` be its digit.\n\nCompute the forced transition `to[v]`:\n- Let `d = dig[v]`.\n- Candidate `(nx, ny) = (x + a[d], y + b[d])`.\n- If inside the grid: `to[v] = id(nx,ny)`, else `to[v] = v` (self-loop).\n\nSo the directed graph is **functional**: every vertex has outdegree exactly 1. \nHence each weakly connected component contains exactly one directed cycle, with directed trees feeding into it.\n\nWe will also build the reverse adjacency list:\n\\[\nrev[u] = \\{ v \\mid to[v] = u \\}.\n\\]\n\n---\n\n### 2) Convert the “write some visited digits” condition to a subsequence problem\n\nFix a starting vertex `start`. The forced movement generates an infinite walk:\n\\[\nstart, to[start], to[to[start]], \\dots\n\\]\nWilbur can choose to write or skip at each visited vertex, so the produced string is **exactly a subsequence** of the digit sequence along this walk (and he may stop after finishing the string).\n\nSo for each query string `s`, we need to know whether there exists a start vertex whose walk contains `s` as a subsequence.\n\n---\n\n### 3) Reverse the query and run the process on the reversed graph\n\nLet `s` be a query, length `L`, and let `r = reverse(s)`.\n\nInstead of searching forward for `s` as a subsequence along `to[]`, we search for `r` as a subsequence along a walk in the **reversed graph** that starts on a cycle and moves outward:\n- Reversing time turns “following `to[]`” into “choosing a predecessor from `rev[]`”.\n- Cycles remain cycles after reversing edges.\n- In the reversed functional graph, every component is a directed cycle with directed trees **going out of** the cycle.\n\nThus any reversed-time walk can:\n1) loop around the cycle any number of steps (including 0),\n2) then move outward along tree edges (cannot return to the cycle).\n\nThis matches the idea that forward-time walks eventually enter a cycle and then repeat it forever.\n\n---\n\n### 4) Precompute subsequence “next-state” table for the reversed string\n\nFor each query string `r` (length `L`), build:\n- `nxt[pos][d]` for `pos = 0..L` and digit `d ∈ {0..9}`\n\nInterpretation:\n- `nxt[pos][d]` = the new position after greedily consuming digit `d` starting from `pos`:\n - if `pos < L` and `r[pos] == d`, then `nxt[pos][d] = pos+1`\n - else `nxt[pos][d] = pos`\n\n(Equivalently, since we only need single-character consume/skip, this is just a constant-time transition.)\n\nSo consuming along any digit sequence becomes repeated application of `pos = nxt[pos][digit]`.\n\n---\n\n### 5) DFS with dominance pruning from cycles in the reversed graph\n\nFor a fixed query, we perform a reachability-style DP over states `(v, pos)`:\n- `v` is a vertex,\n- `pos` is how many characters of `r` have been matched so far.\n\nWe maintain an array `bestPos[v]` initialized to `-1`.\nMeaning: we have already reached vertex `v` with some matched prefix length `bestPos[v]`, and any future arrival with `pos ≤ bestPos[v]` is useless (it cannot lead to matching more of `r` than what we already could from `v`).\n\nDFS routine `dfs(v, pos)`:\n1) If `pos == L`, we can stop: answer is `YES`.\n2) Let `pos2 = nxt[pos][dig[v]]` (choose to write if it matches next, else effectively skip).\n3) If `pos2 <= bestPos[v]`, return (dominated).\n4) Set `bestPos[v] = pos2`.\n5) For each predecessor `u` in `rev[v]`, call `dfs(u, pos2)`.\n\nWe must allow starting points that can loop on cycles to gain matches before leaving.\nTo handle looping, for each directed cycle we do:\n- pick any cycle vertex as root,\n- traverse the cycle edges in order and repeatedly relax `bestPos` on cycle vertices until no improvement occurs (at most `L` improvements total across the cycle because `bestPos` increases and is bounded by `L`),\n- from the cycle vertices, launch `dfs` into outgoing tree edges (their `rev[]` children not on the cycle).\n\nIf any DFS reaches `pos == L`, print `YES`; otherwise `NO`.\n\nBecause `Σ = 10` and the graph size is at most `40000`, this pruning-based DFS runs fast in practice, and the total work is bounded by `O(V * Σ + L)` per query under the functional-graph structure and the monotonic `bestPos` pruning.\n\n---\n\n### 6) Output\n\nRun the above per query string and print `YES` / `NO`.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given a tree with `n` vertices (`1` to `n`). Vertex `v` has color `c_v ∈ [1..n]`.\n\nA simple path is **beautiful** if:\n1. it has at least 2 vertices;\n2. its endpoints have the same color;\n3. no other vertex on the path has that endpoint color.\n\nPaths are **undirected**.\n\n### Input\n- `n` (`2 ≤ n ≤ 2·10^5`)\n- colors `c_1, ..., c_n`\n- `n-1` edges\n\n### Output\nOutput the number of beautiful simple paths.", "rubrics": [{"criterion": "Does the answer define a rooted tree (choose any root, e.g. 1) and process vertices in postorder (children before parent)?", "weight": 10}, {"criterion": "Does the answer define cnt[v][x] as the number of vertices of color x in subtree(v) such that the path from v to that vertex contains no other vertex of color x (i.e., x-top-level w.r.t. v)?", "weight": 10}, {"criterion": "Does the answer state that for any vertex v and any color x ≠ c[v], the number of beautiful paths whose LCA is v and whose endpoints have color x equals the sum over pairs of distinct children subtrees: (top-level x count in child A) × (top-level x count in child B)?", "weight": 20}, {"criterion": "Does the answer state that for x = c[v], no beautiful path can have endpoints in two different child subtrees with LCA=v (because v would be an internal vertex of color x), so only paths (v, w) are allowed for x=c[v]?", "weight": 10}, {"criterion": "Does the answer include the exact counting rule at vertex v for color c[v] as: add totalCv to the answer, where totalCv is the total number of c[v]-top-level vertices across all children of v?", "weight": 10}, {"criterion": "Does the answer update the carried map at v by setting cnt[v][c[v]] = 1 (representing vertex v itself) and not propagating any descendant top-level vertices of color c[v] above v?", "weight": 10}, {"criterion": "Does the answer describe a small-to-large (DSU-on-tree) merge where the largest child map is reused and all other child maps are merged into it, adding cross-pair contributions as ans += big[x] * small[x] for each x ≠ c[v] during the merge?", "weight": 10}, {"criterion": "Does the answer state that each undirected beautiful path is counted exactly once by counting it at the LCA of its endpoints (or an equivalent unique-counting argument)?", "weight": 10}, {"criterion": "Does the answer state a valid complexity bound for the DSU-on-tree implementation, e.g. O(n log^2 n) with ordered maps (or expected O(n log n) with hash maps), for n ≤ 2·10^5?", "weight": 10}], "golden_answer": "### Expert Solution\n\nRoot the tree arbitrarily (e.g. at vertex 1) and process vertices in postorder.\n\n#### 1) Top-level counts\nFor each vertex `v`, maintain a map `cnt[v]` where:\n\n`cnt[v][x] = #{ w ∈ subtree(v) : c_w = x and there is no other x on the path v → w }`\n\nSo `w` is **`x`-top-level w.r.t. `v`**.\n\nThis “top-level” property ensures that once a vertex of color `x` is encountered, deeper vertices of color `x` do not propagate above it.\n\n#### 2) Unique counting by LCA\nCount each undirected path exactly once at the **LCA** of its endpoints (in the chosen rooting).\n\nLet `v` have children `u_1, ..., u_k`.\n\n#### 3) Counting contributions at vertex v\n\n- For any color `x ≠ c[v]`:\n choosing endpoints of color `x` from **two different child subtrees** creates a beautiful path with LCA `v`, because `v` is on the path but has color `≠ x`.\n The number of such paths is:\n `∑_{A<B} cnt[u_A][x] · cnt[u_B][x]`\n\n- For color `x = c[v]`:\n endpoints **cannot** be in two different child subtrees with LCA `v`, since then `v` (color `x`) would be an internal vertex on the path, violating the rule.\n The only valid paths of color `c[v]` “through `v`” are `(v, w)` where `w` is `c[v]`-top-level in some child subtree. So add:\n `totalCv = ∑_{u child of v} cnt[u][c[v]]`\n to the answer.\n\n#### 4) Small-to-large merge (DSU-on-tree)\n\nTo compute `cnt[v]` efficiently:\n\n1. Pick the child `u*` with the largest map `cnt[u*]`. Let `big = cnt[u*]`.\n2. Let\n `totalCv = big[c[v]]` (0 if absent)\n then erase key `c[v]` from `big` (descendant top-level `c[v]` must not propagate above `v`).\n3. For each other child `u`:\n - For each `(x, val) ∈ cnt[u]`:\n - if `x = c[v]`: `totalCv += val` (do not merge)\n - else: add cross-pairs `ans += big[x] * val`, then `big[x] += val`\n4. Add `ans += totalCv` (paths `(v, w)` with endpoint color `c[v]`).\n5. Set `big[c[v]] = 1` because `v` itself becomes the only top-level occurrence of its color for ancestors.\n\nFinally set `cnt[v] = big`.\n\n#### 5) Complexity\nSmall-to-large guarantees each key is merged only `O(log n)` times.\n- With ordered maps: `O(n log^2 n)`\n- With hash maps (expected): `O(n log n)`\n\nThis fits `n ≤ 2·10^5`."}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem: Maximum Possible Score of One Player Under Greedy Picks\n\nYou are given `n` distinct items labeled `1..n`, with exactly one copy of each item. Each item `i` has an integer score `v[i]` (scores may be negative).\n\nTwo players, **A** and **B**, each have a complete ranking (a permutation) of the items:\n\n- `A[1..n]`: player A’s preference list from most preferred to least preferred \n- `B[1..n]`: player B’s preference list from most preferred to least preferred\n\nThe shop starts with all items available. Over exactly `n` turns, the following happens:\n\n- On each turn, **either** A **or** B visits the shop (the order of visitors is not fixed).\n- The visiting player takes the **highest-ranked item in their own list that is still available**.\n\nAfter `n` turns, all items are taken and each player ends up with a set of items.\n\nYour task: among all possible valid visit orders (i.e., all ways to choose who moves on each turn), compute the **maximum possible total score** of the items obtained by player **A**, where total score is the sum of `v[i]` over items A receives.\n\nIt can be proven that different visit orders can lead to different sets for A.\n\n---\n\n### Input\n\nThe first line contains an integer `t` — the number of test cases. \n`1 ≤ t ≤ 10^4`\n\nFor each test case:\n\n- An integer `n` (`1 ≤ n ≤ 2·10^5`)\n- A line with `n` integers `v[1], v[2], ..., v[n]` (`-10^9 ≤ v[i] ≤ 10^9`)\n- A line with permutation `A[1..n]` of `1..n`\n- A line with permutation `B[1..n]` of `1..n`\n\nConstraint: the sum of `n` over all test cases is at most `2·10^5`.\n\n---\n\n### Output\n\nFor each test case, output a single integer: the maximum possible sum of scores of items that player A can end up with.\n", "rubrics": [{"criterion": "Does the response define p[i] as Bob’s position of item a[i] in Bob’s permutation?", "weight": 10}, {"criterion": "Does the response state the DP initialization dp[0] = 0?", "weight": 10}, {"criterion": "Does the response state that the final answer equals max(dp[j]) over j from 0 to n?", "weight": 10}, {"criterion": "Does the response specify a segment-tree range-maximum query over the index interval j in [0, p[i]−1] to compute bestPrefix for item i?", "weight": 10}, {"criterion": "Does the response define a relabeling where item i corresponds to the original item a[i]?", "weight": 10}, {"criterion": "Does the response define a DP state dp[j] as the maximum total value Alice can obtain with current maximum Bob-rank equal to j?", "weight": 10}, {"criterion": "Does the response state that assigning item i to Alice is allowed only for DP states with j < p[i]?", "weight": 10}, {"criterion": "Does the response state that assigning item i to Bob updates the maximum Bob-rank to max(j, p[i])?", "weight": 10}, {"criterion": "Does the response specify a segment-tree range-add update of +val[i] applied to dp[j] over the index interval j in [0, p[i]−1]?", "weight": 10}, {"criterion": "Does the response specify the point update dp[p[i]] := max(dp[p[i]], bestPrefix) after processing item i?", "weight": 10}], "golden_answer": "### 1) Renaming so that Alice’s list becomes `1,2,...,n`\n\nLet the original item IDs be `1..n`. Define:\n\n- `a[1..n]`: Alice’s permutation (most preferred first)\n- `b[1..n]`: Bob’s permutation\n- `v[id]`: value of item `id`\n\nRelabel items by **Alice-rank**:\n\n- The item with Alice-rank `i` is `id = a[i]`.\n- Define `val[i] = v[a[i]]`.\n- Let `pos[id]` be Bob’s rank of item `id` in `b` (i.e., `pos[b[j]] = j`).\n- Define `p[i] = pos[a[i]]`.\n\nAfter this transformation, we can think of items as `1..n` in Alice’s priority order, with:\n- value `val[i]`\n- Bob-rank `p[i]`\n\nThis does not change which outcomes are possible; it only renames items.\n\n---\n\n### 2) Which subsets can Alice end up with?\n\nSuppose Alice finally gets a set `S` of Alice-ranks. Consider any pair:\n- `x ∉ S` (Bob gets `x`)\n- `y ∈ S` (Alice gets `y`)\nwith `x < y` (Alice likes `x` more than `y`).\n\nA necessary condition is:\n\n> `p[x] < p[y]`.\n\nReason: \nIf `p[x] > p[y]`, then Bob prefers `y` earlier than `x`, but Alice prefers `x` earlier than `y`. Under greedy picking, neither `x` nor `y` can be taken first without blocking the other, so such a final split is impossible.\n\nIt turns out this condition is also sufficient: if it holds for all such pairs, a valid visit order exists that realizes exactly `S` (you can schedule Bob to “clear” items until Alice’s next desired item becomes her current greedy choice).\n\nSo the problem becomes:\n\n> Choose a subset `S` maximizing `sum(val[i] for i in S)` such that \n> for every `x ∉ S`, `y ∈ S`, `x < y` implies `p[x] < p[y]`.\n\n---\n\n### 3) DP formulation using the maximum Bob-rank seen so far\n\nProcess items in increasing Alice-rank `i = 1..n`.\n\nLet `dp[j]` mean:\n\n- after deciding ownership of the first `i` items,\n- the maximum Bob-rank among items assigned to Bob equals `j`,\n- `dp[j]` is the maximum achievable sum of values assigned to Alice.\n\nHere `j` ranges from `0..n`, where `j = 0` means Bob has taken nothing yet.\n\nInitialization:\n- `dp[0] = 0`\n- `dp[j] = -∞` for `j > 0`\n\nNow process item `i` with Bob-rank `p = p[i]` and value `val = val[i]`.\n\n**Case A: Alice takes item `i`** \nThis is allowed exactly when `p > j` (all earlier Bob-taken items have smaller Bob-rank). \nState `j` stays the same, value increases:\n\n- for all `j < p`: `dp_next[j] = dp[j] + val`\n\n**Case B: Bob takes item `i`** \nValue does not change, new max Bob-rank becomes `max(j, p)`:\n\n- if `j ≥ p`: it remains in state `j`\n- if `j < p`: it moves to state `p`\n\n---\n\n### 4) Segment tree optimization (O(n log n))\n\nThe transition above can be implemented in-place on a segment tree over indices `j = 0..n` storing current `dp[j]`.\n\nFor item `(p, val)`:\n\n1. Compute:\n - `bestPrefix = max(dp[j])` over `j in [0, p-1]`\n\n2. Apply Alice-taking updates:\n - For all `j in [0, p-1]`, do `dp[j] += val`\n - This is a **range add**.\n\n3. Apply Bob-taking update into state `p`:\n - `dp[p] = max(dp[p], bestPrefix)`\n - This is a **point chmax** after a range max query.\n\nNote:\n- States `j > p` are unchanged in this step.\n- State `p` already contains the `j = p` “Bob keeps max = p” option, and the `bestPrefix` handles all `j < p` moving into `p`.\n\nAfter processing all `n` items, the answer is:\n- `max(dp[j])` over `j = 0..n`\n\nData structure requirements:\n- range add\n- range maximum query\n- point update to set `dp[p] := max(dp[p], x)`\n\nA lazy segment tree supports these in `O(log n)` each, giving total complexity `O(n log n)` per test file (with `sum n ≤ 2·10^5`).\n\n---\n\n### 5) Summary of implementation steps\n\nFor each test case:\n1. Read `v`, `a`, `b`.\n2. Build `pos[id]` from `b`.\n3. Build arrays for `i = 1..n`:\n - `val[i] = v[a[i]]`\n - `p[i] = pos[a[i]]`\n4. Initialize segment tree with `dp[0]=0`, others `-∞`.\n5. For `i=1..n`, perform the three operations described above.\n6. Output the maximum stored `dp[j]`."}
{"domain": "Algorithms & Data Structures", "prompt": "You have a strip of `1 × 10^9` cells numbered `1` to `10^9`.\n\nThere are `n` snakes (numbered `1` to `n`). Initially, each snake occupies exactly one cell, and no two snakes can be placed in the same cell. After placement, the game runs for `q` seconds. Each second exactly one event occurs:\n\n- **Snake `s_i` enlarges:** if it currently occupies `[l, r]`, it becomes `[l, r+1]`.\n- **Snake `s_i` shrinks:** if it currently occupies `[l, r]`, it becomes `[l+1, r]`.\n\nIf at any time any snake hits an obstacle (another snake or the end of the strip), you lose. Otherwise, you win with a score equal to the maximum cell index occupied by any snake at any time.\n\nGiven the sequence of `q` events (guaranteed valid: a snake of length 1 never shrinks), find the minimum possible score over all initial placements.\n\n## Input\n- First line: integers `n, q` (`1 ≤ n ≤ 20`, `1 ≤ q ≤ 2 · 10^5`).\n- Next `q` lines: either `\"s_i +\"` or `\"s_i -\"`.\n\n## Output\nOutput one integer — the minimum possible score.", "rubrics": [{"criterion": "Does the solution state the final answer as min over last of ( d[(1<<n)-1][last] + plusCount[last] ), where plusCount[k] is the number of '+' events of snake k?", "weight": 20}, {"criterion": "Does the solution state the score for a fixed permutation p1..pn as 1 + (sum of gaps between consecutive snakes) + (number of '+' events of the last snake pn)?", "weight": 10}, {"criterion": "Does the solution state that choosing an order of snakes on the strip corresponds to choosing a permutation of the n snakes?", "weight": 10}, {"criterion": "Does the solution define (for an ordered pair (i,j) with j immediately to the right of i) that an event contributes e=−1 when snake i enlarges and e=+1 when snake j shrinks (and e=0 otherwise) to the evolution of the gap?", "weight": 10}, {"criterion": "Does the solution state the DP base case d[1<<i][i] = 1 for every snake i?", "weight": 10}, {"criterion": "Does the solution state that for a fixed permutation, it is optimal to place snakes greedily as close together as possible (i.e., using the minimum feasible gaps between consecutive snakes)?", "weight": 10}, {"criterion": "Does the solution give the exact formula for minDist[i][j] as 1 − min_prefix_sum of the cumulative e-values over all events (equivalently, minDist[i][j] = -min_{1..q})?", "weight": 10}, {"criterion": "Does the solution define the DP state d[mask][last] as the minimum possible starting cell (position) of snake 'last' after placing exactly the set 'mask' in some order, with the first placed snake starting at cell 1?", "weight": 10}], "golden_answer": "## Expert Answer\n\nKey idea: placing snakes left-to-right defines a permutation; for any fixed order the best placement is greedy (minimum feasible gaps), and we can compute the required minimum gaps from the event log.\n\n### 1) Reduce to an order (permutation)\nIn any valid placement, the snakes appear left-to-right in some permutation `p_1, p_2, ..., p_n`. If this permutation is fixed, it is optimal to place them as close as possible (use the smallest initial gaps that still avoid collisions during all events), because any extra initial spacing only increases the maximum occupied cell.\n\n### 2) Score for a fixed permutation\nLet the initial gap between consecutive snakes `p_k` and `p_{k+1}` be `g_k`. Then:\n`score(p) = 1 + ∑_{k=1..n-1} g_k + plusCount(p_n)`\nbecause the first snake can start at cell 1, the last snake starts at `1 + ∑ g_k`, and only enlargements of the last snake can push the global maximum further right.\n\n### 3) Compute `minDist[i][j]` for \"`j` immediately right of `i`\"\nAssume snake `j` is immediately to the right of snake `i` with initial gap `x`. The gap changes only when:\n- snake `i` enlarges (gap `-1`),\n- snake `j` shrinks (gap `+1`).\n\nDefine per-event contribution `e_t` for ordered pair `(i, j)`:\n- `e_t = -1` if event `t` is \"`i` +\",\n- `e_t = +1` if event `t` is \"`j` -\",\n- `e_t = 0` otherwise.\n\nAfter `t` events the gap is `x + ∑_{u=1..t} e_u`. We need this `≥ 0` for all `t`, so:\n`minDist[i][j] = 1 - min_{1 ≤ t ≤ q} (∑_{u=1..t} e_u)`\n(This equals `-min(...) + 1`).\n\n### 4) Choose the best permutation via bitmask DP\nLet `d[mask][last]` be the minimum possible starting cell of snake `last` after placing exactly the set `mask` in some order, with the first placed snake starting at cell 1.\n\nBase:\n`d[1 << i][i] = 1` for all `i`.\n\nTransition:\n`d[mask | (1 << j)][j] = min_{i ∈ mask} (d[mask][i] + minDist[i][j])`\n\nFinal answer:\n`min_{1 ≤ last ≤ n} ( d[(1 << n) - 1][last] + plusCount(last) )`"}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem\n\nDenis defines a non-commutative “multiplication” of strings. \nFor a string `s` of length `m` and a string `t`, define:\n\n\\[\ns \\cdot t = t + s_1 + t + s_2 + \\dots + t + s_m + t\n\\]\n\nwhere \\(s_i\\) is the \\(i\\)-th character of `s`, and `+` means concatenation.\n\nExamples:\n- `\"abc\"\"de\" = \"deadebdecde\"`\n- `\"ab\"\"z\" = \"zazbz\"`\n\nRoman defines the **beauty** of a string as the length of the longest substring consisting of only one repeated character (i.e., the maximum run length).\n\nYou are given `n` strings \\(p_1, p_2, \\dots, p_n\\). Compute the beauty of:\n\n\\[\n(\\dots(((p_1 \\cdot p_2)\\cdot p_3)\\cdot \\dots)\\cdot p_n)\n\\]\n\nIt is guaranteed that the beauty of the final product is at most \\(10^9\\).\n\n### Input\n- First line: integer \\(n\\) \\((2 \\le n \\le 10^5)\\)\n- Next \\(n\\) lines: non-empty strings \\(p_1,\\dots,p_n\\) of lowercase English letters\n\nConstraints:\n- Total length of all \\(p_i\\) is at most \\(10^5\\)\n- Final beauty is at most \\(10^9\\)\n\n### Output\nPrint one integer — the beauty of the final product.\n", "rubrics": [{"criterion": "The answer states that the operation satisfies associativity: (a·b)·c = a·(b·c).", "weight": 10}, {"criterion": "The answer computes the product by folding from right to left using P_n = p_n and P_i = p_i · P_{i+1}?", "weight": 10}, {"criterion": "The answer introduces a capping constant INF equal to 10^9 (or an explicitly stated value greater than or equal to 10^9) for tracked lengths.", "weight": 10}, {"criterion": "The answer defines a boolean field allSame(X) that indicates whether all characters in X are equal.", "weight": 10}, {"criterion": "The answer defines the concatenation cross-run value as A.suffLen + B.prefLen when A.suffChar equals B.prefChar.", "weight": 10}, {"criterion": "The answer defines best(A+B) as the maximum of A.best, B.best, and the cross-run value for the concatenation boundary.", "weight": 10}, {"criterion": "The answer gives the prefix-length update rule prefLen(A+B) = A.len + B.prefLen when A.allSame is true and A.prefChar equals B.prefChar.", "weight": 10}, {"criterion": "The answer gives the suffix-length update rule suffLen(A+B) = B.len + A.suffLen when B.allSame is true and A.suffChar equals B.suffChar.", "weight": 10}, {"criterion": "The answer describes computing s·t by initializing res as the summary of t and then applying the loop res=merge(res,single(c)) followed by res=merge(res,tSummary) for each character c of s.", "weight": 10}, {"criterion": "The solution states an overall runtime of O(total input length) (i.e., O(∑|pi|)) for the full computation.", "weight": 10}], "golden_answer": "### 1) Use associativity and fold from right to left\n\nThe operation is associative:\n\\[\n(a\\cdot b)\\cdot c = a\\cdot(b\\cdot c)\n\\]\n(you can verify by expanding both sides; both produce alternating blocks of the right operand with single characters of the left operands inserted in the same order).\n\nSo instead of building the product left-to-right (which can temporarily explode and later “collapse”), we compute:\n\\[\nP_i = p_i \\cdot P_{i+1}, \\quad P_n = p_n\n\\]\nfrom \\(i=n-1\\) down to \\(1\\).\n\nBecause the final beauty is guaranteed \\(\\le 10^9\\), when folding right-to-left we can safely cap all tracked lengths at \\(INF=10^9\\) (or \\(10^9+5\\)) to avoid overflow without affecting the answer.\n\n---\n\n### 2) Maintain only a compact summary of a string\n\nFor any (possibly huge) string \\(X\\), store the tuple:\n\n- `len(X)` (capped to `INF`)\n- `best(X)`: maximum run length anywhere in \\(X\\)\n- `prefChar(X)`, `prefLen(X)`: character and length of the maximal constant prefix\n- `suffChar(X)`, `suffLen(X)`: character and length of the maximal constant suffix\n- `allSame(X)`: whether all characters in \\(X\\) are equal\n\nThis is sufficient to compute the same tuple for concatenations.\n\nFor a single character `c`:\n- `len=1`, `best=1`\n- `prefChar=suffChar=c`, `prefLen=suffLen=1`\n- `allSame=true`\n\nFor an explicit input string, compute the tuple by a linear scan.\n\n---\n\n### 3) Concatenation merge routine\n\nLet `merge(A,B)` return the summary for the concatenation \\(AB\\). With `INF` capping:\n\n- `len = min(INF, A.len + B.len)`\n- `prefChar = A.prefChar`\n- `prefLen`:\n - if `A.allSame` and `A.prefChar == B.prefChar` then `min(INF, A.len + B.prefLen)`\n - else `A.prefLen`\n- `suffChar = B.suffChar`\n- `suffLen`:\n - if `B.allSame` and `A.suffChar == B.suffChar` then `min(INF, B.len + A.suffLen)`\n - else `B.suffLen`\n- `allSame = A.allSame && B.allSame && (A.prefChar == B.prefChar)`\n- `best = max(A.best, B.best, cross)` where\n - `cross = (A.suffChar == B.prefChar) ? min(INF, A.suffLen + B.prefLen) : 0`\n\n---\n\n### 4) How to compute `s ⋅ t` using only merges\n\nBy definition:\n\\[\ns\\cdot t = t + s_1 + t + s_2 + \\dots + t + s_m + t\n\\]\n\nSo if we already have the summary of \\(t\\) as `T`, and `s` is an explicit string of length `m`, we can build the summary of \\(s\\cdot t\\) as:\n\n- `res = T`\n- for each character `c` in `s` from left to right:\n - `res = merge(res, single(c))`\n - `res = merge(res, T)`\n\nThis performs \\(O(|s|)\\) merges.\n\n---\n\n### 5) Full algorithm\n\n- Read all strings \\(p_1,\\dots,p_n\\).\n- Set `cur = summary(p_n)`.\n- For `i = n-1` down to `1`:\n - Let `T = cur` (summary of the current right operand).\n - Compute `cur = summary(p_i ⋅ current)` by the loop in section 4 using merges and `T`.\n- Output `cur.best`.\n\nComplexity:\n- Each character of each input string is processed a constant number of times.\n- Total time \\(O(\\sum |p_i|)\\), total memory \\(O(1)\\) besides storing the input and small summaries.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "An autonomous vehicle navigation system uses a bidirectional time-dependent Dijkstra algorithm to compute an optimal route on a directed graph\nG with 12 nodes labeled N0 through N11 and the following directed edges with base travel times in seconds:\n\n(N0,N1,45), (N0,N2,60), (N1,N3,50), (N1,N4,70), (N2,N4,55), (N2,N5,80),\n(N3,N6,65), (N4,N6,40), (N4,N7,90), (N5,N7,60), (N5,N8,75),\n(N6,N9,55), (N7,N9,50), (N7,N10,85), (N8,N10,70),\n(N9,N11,45), (N10,N11,40).\n\nTravel times depend on the start time of traversal of each edge as follows:\n\n• For any traversal that begins between t = 0 and t = 120 seconds, if the edge is incident to node N4 (either entering or leaving N4), its base weight is multiplied by 1.8.\n• For any traversal that begins between t = 120 and t = 240 seconds, if the edge is incident to node N7, its base weight is multiplied by 2.2.\n• Outside these windows, all edges use their base weights.\n\nThe vehicle departs from node N0 at time t = 0.\n\nAlgorithm Definition (Deterministic)\n\nThe algorithm runs a forward search from N0 and a backward search from N11 using the following rules:\n\n1. Priority Queues\n\nEach search maintains its own min-heap priority queue ordered by cumulative cost.\nTies inside a queue are broken by smaller node index (e.g., N3 < N4).\n\n2. Expansion Scheduling\n\nAt each iteration, the algorithm compares the minimum keys in the forward and backward priority queues and expands the node with the smaller key.\nIf the two minimum keys are equal, the forward queue is expanded.\n\n3. Forward Search Cost Model\n\nThe forward search computes exact arrival times using the time-dependent cost rules above.\nWhen relaxing an edge (u,v), the traversal start time equals the arrival time at u, and the edge cost is multiplied if u or v is N4 or N7 and the traversal start time lies in the corresponding time window.\n\n4. Backward Search Cost Model (Before First Complete Path)\n\nBefore any complete N0→N11 path is discovered, the backward search computes distances using base edge weights only, treating them as admissible lower bounds.\n\n5. Backward Search Cost Model (After First Complete Path)\n\nAfter a complete path with total cost C* is discovered, the backward search recomputes all subsequent relaxations using the same time-dependent cost model as the forward search, assuming arrival at N11 occurs at time C*.\n\n6. Meeting Condition\n\nA node is defined to be a meeting node when it has been expanded (popped from the priority queue) in both the forward and backward searches.\n\nThe first such node encountered is recorded as the meeting node.\n\n7. Path Reconstruction\n\nThe full path is constructed by concatenating the forward parent chain from N0 to the meeting node and the backward parent chain from the meeting node to N11.\n\n8. Termination Condition\n\nThe algorithm terminates when:\n\nmin_key_forward + min_key_backward > best_complete_path_cost\n\nwhere:\n• min_key_forward is the smallest key currently in the forward queue,\n• min_key_backward is the smallest key currently in the backward queue,\n• best_complete_path_cost is the lowest-cost N0→N11 path found so far.\n\nThese values are evaluated immediately after each node expansion.\n\n9. Priority Queue Insertions\n\nEvery insertion into either priority queue is counted, including duplicate insertions caused by cost improvements.\n\nTask\n\nDetermine:\n\n(1) the exact sequence of nodes expanded by the forward search until termination,\n(2) the exact sequence of nodes expanded by the backward search until termination,\n(3) the first meeting node,\n(4) the optimal path from N0 to N11,\n(5) the total travel time of that path in seconds, and\n(6) the total number of nodes inserted into priority queues across both searches.", "rubrics": [{"criterion": "Does the answer state the forward expansion sequence exactly as [N0, N1, N2, N3, N5, N4, N6, N8, N9]?", "weight": 20}, {"criterion": "Does the answer state the backward expansion sequence exactly as [N11, N10, N9, N7, N6, N8, N5, N4]?", "weight": 20}, {"criterion": "Does the answer identify N9 as the first meeting node?", "weight": 20}, {"criterion": "Does the answer give the optimal path exactly as N0 → N1 → N3 → N6 → N9 → N11?", "weight": 10}, {"criterion": "Does the answer compute the total travel time as exactly 260 seconds?", "weight": 10}, {"criterion": "Does the answer report the total priority queue insertion count as exactly 24?", "weight": 10}, {"criterion": "Does the answer explicitly show that no N4- or N7-incident edges are used in the optimal path?", "weight": 10}, {"criterion": "Does the answer demonstrate that termination occurs because min_forward_key + min_backward_key > 260?", "weight": 10}], "golden_answer": "(1) Forward Expansion Sequence\n\nForward search starts at N0 at time t = 0 and applies time-dependent weights.\n\nExpand N0 (0)\n→ insert N1(45), N2(60)\n\nExpand N1 (45)\n→ insert N3(95), N4(171) [70 × 1.8 due to N4 window]\n\nExpand N2 (60)\n→ update N4(159) [55 × 1.8], insert N5(140)\n\nExpand N3 (95)\n→ insert N6(160)\n\nExpand N5 (140)\n→ insert N7(272) [60 × 2.2 due to N7 window], insert N8(215)\n\nExpand N4 (159)\n→ attempt update N6(199), ignored (existing 160 is better)\n\nExpand N6 (160)\n→ insert N9(215)\n\nExpand N8 (215)\n→ insert N10(285)\n\nExpand N9 (215)\n→ insert N11(260)\n\nAt this point, best complete path cost = 260.\nNext forward key = 272, next backward key = 155, and\n272 + 155 > 260 ⇒ termination.\n\nForward Expansion Order:\n[N0, N1, N2, N3, N5, N4, N6, N8, N9]\n\n(2) Backward Expansion Sequence\n\nBackward search begins at N11 using base weights until first complete path.\n\nExpand N11 (0)\n→ insert N9(45), N10(40)\n\nExpand N10 (40)\n→ insert N7(125), N8(110)\n\nExpand N9 (45)\n→ update N7(95), insert N6(100)\n\nExpand N7 (95)\n→ insert N4(185), insert N5(155)\n\nExpand N6 (100)\n→ insert N3(165)\n\nExpand N8 (110)\n→ no improvements\n\nExpand N5 (155)\n→ insert N2(235)\n\nExpand N4 (185)\n→ insert N1(255)\n\nTermination condition satisfied:\n272 + 155 > 260.\n\nBackward Expansion Order:\n[N11, N10, N9, N7, N6, N8, N5, N4]\n\n(3) First Meeting Node\n\nN9 is expanded in:\n• forward search after N6\n• backward search after N11\n\nNo earlier node is expanded in both searches.\n\nMeeting Node: N9\n\n(4) Optimal Path\n\nForward parents:\nN0 → N1 → N3 → N6 → N9\n\nBackward parents:\nN9 → N11\n\nCombined path:\n\nN0 → N1 → N3 → N6 → N9 → N11\n\n(5) Total Travel Time\n\nNo N4 or N7 edges appear on this path, so no multipliers apply.\n\nN0 → N1 = 45\nN1 → N3 = 50\nN3 → N6 = 65\nN6 → N9 = 55\nN9 → N11 = 45\n\nTotal:\n\n45 + 50 + 65 + 55 + 45 = 260 seconds\n\n(6) Total Priority Queue Insertions\n\nEach discovery or cost-improving update counts.\n\nForward insertions (12):\nN1, N2\nN3, N4\nupdate N4, N5\nN6\nN7, N8\nN9\nN10\nN11\n\nBackward insertions (12):\nN9, N10\nN7, N8\nupdate N7, N6\nN4, N5\nN3\nN2\nN1\n\nTotal insertions:\n\n12 + 12 = 24"}
{"domain": "Algorithms & Data Structures", "prompt": "A miner is searching a rooted underground shaft system that forms a **tree** of `n` chambers (nodes) connected by one-way-less tunnels (undirected edges). A single phantom hides in exactly one chamber; initially it may be in any chamber. The miner can perform two kinds of actions. After each action, the phantom may (or may not) move to one adjacent chamber, except it is forbidden to move into the chamber that the miner just inspected in that same action.\n\nAvailable actions (each targets a single chamber `x`):\n\n- `1 x` — **Inspect** chamber `x`. If the phantom is currently in `x`, the miner catches it and the process ends. Otherwise the phantom may move to any adjacent chamber except `x`.\n- `2 x` — **Seal** chamber `x`: destroy every tunnel incident to `x`. After sealing, the phantom cannot use those destroyed tunnels. Then the phantom may move to one adjacent chamber (along any remaining tunnels).\n\nDesign a single strategy — i.e., an explicit sequence of actions — that guarantees the miner will catch the phantom regardless of its initial position and its choices of moves. Your sequence must contain at most `⌊5n/4⌋` actions.\n\n## Input\n\nThe input contains multiple test cases. The first line contains a single integer `t` (`1 ≤ t ≤ 10^4`) — the number of test cases. The sum of `n` over all test cases does not exceed `2·10^5`.\n\nEach test case has the following format:\n\n- A line with an integer `n` (`2 ≤ n ≤ 2·10^5`) — the number of chambers.\n- Then `n-1` lines follow, each with two integers `u` and `v` (`1 ≤ u, v ≤ n`), indicating an undirected tunnel between chambers `u` and `v`. The tunnels form a tree.\n\n## Output\n\nFor each test case, output a sequence of actions that will surely catch the phantom.\n\nFirst print a single integer `k` (`1 ≤ k ≤ ⌊5n/4⌋`) — the number of actions in your strategy.\n\nThen print `k` lines; the `i`-th such line should contain two integers `ti` and `xi`:\n\n- `ti` is either `1` or `2`, specifying the action type (inspect or seal).\n- `xi` is the target chamber index (`1 ≤ xi ≤ n`).\n\nIf the miner inspects a chamber and the phantom happens to be there, the process stops immediately (no further actions are performed). Your printed sequence should therefore be a valid plan that would succeed in every possible adversarial scenario (the grader will verify your action list satisfies the bound and would lead to capture irrespective of phantom moves).\n\n## Constraints summary\n\n- `1 ≤ t ≤ 10^4`\n- `2 ≤ n ≤ 2·10^5`\n- Sum of `n` across all test cases ≤ `2·10^5`\n- Output sequence length per test case must satisfy `k ≤ ⌊5n/4⌋`\n\n## Notes\n\n- You do **not** need to minimize `k`, only ensure `k ≤ ⌊5n/4⌋` and that the strategy guarantees capture.\n- The judge will simulate the worst-case adversarial phantom behavior to check your plan.", "rubrics": [{"criterion": "Does the solution include a postorder coloring procedure that specifies how to label each node as 'green', 'yellow', or 'black' using only information from its children?", "weight": 10}, {"criterion": "Does the solution assert that after removing every node labeled 'black', every connected component of the remaining graph is a simple path (every node has residual degree ≤ 2)?", "weight": 10}, {"criterion": "Does the solution state that groups associated with different black nodes are pairwise disjoint?", "weight": 10}, {"criterion": "Does the solution derive the inequality n ≥ 4·b where b denotes the number of black nodes?", "weight": 10}, {"criterion": "Does the solution state that when a node is colored black because it has three or more green children, it is grouped with three distinct green-subtree endpoint vertices (i.e., the solution explicitly assigns three distinct green vertices to that black node)?", "weight": 10}, {"criterion": "Does the solution state that the worst-case total number of operations equals n + b and then conclude this value is ≤ ⌊5n/4⌋?", "weight": 10}, {"criterion": "Does the solution state the algorithmic resource bounds as O(n) time and O(n) memory for producing the operation sequence?", "weight": 10}, {"criterion": "Does the solution explicitly state that all type-2 (cut) operations are performed before any type-1 (inspect) operations?", "weight": 10}, {"criterion": "Does the solution describe the sweep procedure for a path as performing exactly one type-1 operation per node while checking nodes in sequence from an endpoint to the other endpoint?", "weight": 10}, {"criterion": "Does the solution explicitly justify that moving all type-2 (seal) operations earlier cannot reduce correctness because sealing only restricts the phantom’s movement options?", "weight": 10}], "golden_answer": "**Idea in one line.** \nCut a carefully chosen small set of nodes so the remaining connected pieces are simple paths, then “sweep” each path by checking its nodes from one end to the other. Do all cuts first (they only restrict the phantom), then do the sweeps. The number of cuts is at most `⌊n/4⌋`, so the total number of actions (cuts + checks) is `≤ n + ⌊n/4⌋ = ⌊5n/4⌋`.\n\n---\n\n## Full algorithm (constructive)\n\n1. **Root the tree** at node `1`. We will do a single postorder DFS to compute one of three colors for every node: **green**, **yellow**, or **black**.\n\n2. **Coloring rule (postorder):** for each node `v`, let `G` = number of children of `v` colored **green**, and let `Y` = whether `v` has any child colored **yellow**.\n - If `G ≥ 3` **or** `Y = true`, color `v` **black**.\n - Else if `G = 2` (and `Y = false`), color `v` **yellow**.\n - Else (i.e., `G ≤ 1` and `Y = false`), color `v` **green**.\n\n Compute these colors by visiting children first (postorder), so each child’s color is known when we decide the parent’s color.\n\n3. **Perform all cuts.** For every node `v` colored **black**, output operation `2 v` (destroy all edges incident to `v`). Do these `2`-operations first (in any order).\n\n After cutting every black node, every connected component of the remaining graph is a simple path (this follows from how colors were assigned — nodes with degree ≥3 in the leftover graph were prevented by the coloring).\n\n4. **Sweep each path.** For each connected component (which is now a path of length `k` nodes), choose one endpoint and perform `1 x` operations along the path from that endpoint to the other endpoint (i.e., check first node, then next, …, last), listing `k` operations for that path. Do these sweeps after finishing all `2`-operations.\n\n If any `1 x` finds the phantom, the process stops early (the plan is still valid since we listed a complete schedule for the adversary-free guarantee).\n\n---\n\n## Why this works\n\n- **Doing all `2` first is safe.** Cutting edges only reduces the phantom’s possible moves. Sealing a node only deletes tunnels, so it can only reduce the phantom’s set of legal moves and never creates new moves; therefore performing type-2 operations earlier cannot make capture harder. Hence we may assume all `2`-operations come before any `1`-operation.\n\n- **After the cuts every component is a path.** The coloring rule forbids any node (in the uncut graph) from having three or more “green” child-subpaths survive in its subtree without itself being black. When we cut out every black node (remove all incident edges), every remaining component has no branching — it must be a path (degree ≤ 2 everywhere). Informally: yellow nodes serve only to join two green child-paths into one longer path; black nodes break branches.\n\n- **Sweeping a path of length `k` with `k` checks works.** If you check nodes along the path from one endpoint to the other using `1`-operations, after `i` checks the phantom cannot be located at any of the first `i` nodes (because if it were, it would be caught at that check; otherwise it could not cross back past the last checked node because edges behind black nodes are removed). By induction this eventually forces capture.\n\n---\n\n## Operation count (bound)\n\n- Let `b` be the number of black nodes produced by the coloring. We perform exactly `b` operations of type `2` (one for each black node).\n\n- After removing edges incident to black nodes, the graph splits into disjoint paths covering the `n` nodes. Sweeping every path requires exactly `n` operations of type `1` in total (each node is checked exactly once in the worst-case adversarial schedule). Thus worst-case total operations = `n + b`.\n\n- **Key combinatorial bound:** The coloring guarantees `b ≤ ⌊n/4⌋`. Sketch of charging argument:\n - Every time a node becomes black because it had `≥ 3` green children, choose exactly three of those green children and charge one distinct green-subtree endpoint from each of the three to that black node.\n - Every time a node becomes black because it had a yellow child, charge the yellow child and its (up to) two green children — again three distinct nodes charged to this black node.\n - The groups associated with different black nodes are pairwise disjoint (no vertex is charged to two different black nodes).\n - Hence each black node accounts for at least 4 distinct vertices (the black node itself + at least 3 charged vertices), so n ≥ 4·b.\n\n- Therefore total operations `n + b ≤ n + ⌊n/4⌋ = ⌊5n/4⌋`, meeting the required bound.\n\n---\n\n## Complexity and implementation notes\n\n- The coloring (postorder DFS) runs in `O(n)` time and uses `O(n)` memory (recursion or an explicit stack).\n- Producing the list of cut operations is `O(b)`. After removing black nodes conceptually, extracting the path components and listing sweep orders is `O(n)`.\n- Overall time complexity `O(n)` per test case; total across all tests `O(sum n)`.\n\n---\n\n## Summary (what to output)\n\n- First, output `k = n + b` operations (or fewer — the schedule may stop early if the phantom is caught).\n- Then print:\n 1. `2 v` for every black node `v` (order arbitrary).\n 2. For each remaining path component, a sequence `1 x1`, `1 x2`, …, `1 xk` checking nodes along the path from one endpoint to the other endpoint.\n\nThis produces a valid plan that always catches the phantom and uses at most `⌊5n/4⌋` operations.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "An Arbor Network is an undirected, connected, acyclic graph (i.e., a tree) with N junctions numbered 1 through N.\n\nEvery morning, R rival couriers traverse the network simultaneously. Rival i starts at junction s_i and travels to junction t_i along the unique shortest path in the tree. If that path is the vertex sequence p_1, p_2, ..., p_k with p_1 = s_i and p_k = t_i, then at integer time j (for 1 ≤ j ≤ k) the rival is exactly at vertex p_j.\n\nAfter a rival reaches t_i, they stop moving and cannot be encountered thereafter. Concretely, for rival i, encounters are only possible at times 2, 3, ..., k (while the rival is still traveling); times after reaching the destination are ignored for collision purposes.\n\nA protagonist courier starts at junction A at time 1 and must reach junction B (A ≠ B). At each integer time step, the protagonist may either:\n\nmove along one incident road to an adjacent junction, or\nwait at the current junction.\nA collision occurs if at any integer time t the protagonist and any rival occupy the same junction. (Being on the same edge segment at the same time is allowed.)\n\nIt is guaranteed that s_i ≠ A for all rivals i.\n\nGoal:\nFor each test instance, compute the earliest integer time at which the protagonist can arrive at junction B without ever colliding at a junction with any rival courier. If it is impossible, output -1.\n\nInput:\nThe first line contains an integer T, the number of test instances.\n\nEach test instance:\n\nOne line with four integers N, R, A, B (2 ≤ N ≤ 10^5, 1 ≤ R ≤ 200, 1 ≤ A,B ≤ N, A ≠ B)\nNext N-1 lines: each line has two integers u and v describing an undirected edge of the tree\nNext R lines: each line has two integers s_i and t_i with s_i ≠ t_i and s_i ≠ A\nIt is guaranteed that the sum of all N across test instances does not exceed 10^5.\n\nOutput:\nFor each test instance print one integer: the earliest collision-free arrival time at B, or -1.", "rubrics": [{"criterion": "Does the answer explicitly state the finite search horizon bound t* ≤ 2N + 1?", "weight": 1}, {"criterion": "Does the answer explicitly define a forbidden pair (u, t) as: some rival occupies vertex u at integer time t during its travel?", "weight": 1}, {"criterion": "Does the answer explicitly state the forbidden-pair budget: the total number of forbidden (vertex, time) pairs is at most N·R?", "weight": 1}, {"criterion": "Does the answer explicitly define the base frontier/DP set as S1 = {A}?", "weight": 1}, {"criterion": "Does the answer explicitly state the waiting transition: if v ∈ S_t and (v, t+1) is not forbidden, then v ∈ S_{t+1}?", "weight": 1}, {"criterion": "Does the answer explicitly state the movement transition: if u ∈ S_t, v is adjacent to u, and (v, t+1) is not forbidden, then v ∈ S_{t+1}?", "weight": 1}, {"criterion": "Does the answer explicitly state that the reported arrival time equals min{ t : B ∈ S_t}?", "weight": 1}, {"criterion": "Does the answer explicitly state the failure rule: output −1 if there is no t ≤ 2N + 1 such that B ∈ S_t?", "weight": 1}, {"criterion": "Does the answer explicitly state the combinatorial bound that each vertex can enter the frontier S_t at most R + 1 times over all t?", "weight": 1}, {"criterion": "Does the answer explicitly state the overall time complexity bound O(N·R)?", "weight": 1}], "golden_answer": "Explicit finite time horizon: t* ≤ 2N + 1\nLet t* be the earliest arrival time at B among all collision-free schedules, if any exist.\n\nClaim. If a collision-free schedule exists, then t* ≤ 2N + 1.\n\nReason (sketch). Each rival walks a simple tree path of length at most N, so all rivals have finished moving by time ≤ N, hence encounter constraints cease no later than time N + 1. From time N + 1 onward, the protagonist can ignore rivals and reach any node (in particular B) within at most N more moves in a tree. Therefore some collision-free schedule (if one exists at all) can be made to arrive by (N + 1) + N = 2N + 1. So we only need to search times t ≤ 2N + 1.\n\nForbidden pairs and the budget ≤ N · R\nDefine a vertex-time pair (u, t) as forbidden if at time t some rival occupies vertex u at a time when encounters count (i.e., along their travel times 2 through the path length).\n\nEach rival visits at most N vertices over time, hence contributes at most N forbidden pairs. Therefore the total number of forbidden pairs satisfies:\n{(u, t) forbidden} ≤ N · R.\n\nStore forbidden information as per-time lists: forbidden[t] = list of vertices forbidden at time t. Total stored entries is O(NR).\n\nFormal DP / frontier recurrence (explicit)\nLet S_t ⊆ {1, ..., N} be the set of vertices where the protagonist can be at time t without having collided at any time ≤ t.\n\nBase:\nS_1 = {A}.\n\nTransition (for every t ≥ 1): for each vertex v,\nv ∈ S_{t+1} ⇔ ((v, t+1) is not forbidden) AND (v ∈ S_t OR ∃u ∈ N(v) with u ∈ S_t).\nThis exactly models “wait or move one edge” while avoiding forbidden vertex-time collisions.\n\nOutput rule (explicit):\nanswer = min { t : B ∈ S_t },\nand output -1 if no such t exists with t ≤ 2N + 1.\n\nKey invariant: each vertex enters at most R + 1 times\nUse an incremental frontier computation (do not build a full N × (2N) DP table).\n\nInvariant (explicit). Over all times, any fixed vertex v can become newly feasible (i.e., “enter” the frontier S_t) at most R + 1 times.\n\nJustification (sketch): a vertex can be removed from feasibility at time t only if it is forbidden at t. A given vertex can be forbidden by at most R rivals (each at some time), hence it can be “kicked out” at most R times, so it can enter at most R + 1 times.\n\nIncremental processing and total work bounds\nProcess time steps t = 1, 2, ..., 2N + 1 while maintaining the current feasible set S_t (as a boolean in[v]) and a candidate list for membership tests.\n\nType-1 removals handled incrementally (explicit). At time t, mark all vertices in forbidden[t] as blocked for time t. The total amount of such removal handling over the whole run is:\n∑_t |forbidden[t]| ≤ N · R.\n\nNeighbor-announcement bound (explicit). Each time a vertex v enters the frontier, we may “announce” its neighbors as candidates for the next time. Since v enters at most R + 1 times, the total neighbor-announcement work is bounded by:\n∑_v deg(v) · (R + 1) = (R + 1) ∑_v deg(v) = (R + 1) · 2(N − 1) ≤ 2N(R + 1).\n\nTotal candidate processing (explicit). Candidates arise only from:\n\nforbidden-event triggers (bounded by N · R), and\nneighbor announcements (bounded by 2N(R + 1)).\nThus, the total number of candidate checks processed over all times is O(NR).\nFinal complexities (explicit)\nTime complexity: O(NR), justified by combining:\n\nforbidden-event processing ≤ N · R, and\nneighbor announcements ≤ 2N(R + 1),\nplus O(1)-amortized candidate checks per announced item.\nMemory complexity: O(NR) for storing forbidden per-time lists (total entries ≤ N · R) plus O(N) for the tree adjacency and frontier arrays; overall O(NR)."}
{"domain": "Algorithms & Data Structures", "prompt": "Consider an n x m grid (2 <= n <= 12, 2 <= m <= 1000) where some cells are blocked. A Hamiltonian path visits every non-blocked cell exactly once. The task is to count Hamiltonian paths from cell (0,0) to cell (n-1, m-1), modulo 10^9+7. The grid is given as n lines of m characters where '.' is empty and '#' is blocked. If (0,0) or (n-1, m-1) is blocked, the answer is 0.\n\nDescribe a complete algorithm to solve this problem using broken profile dynamic programming (plug DP). Your answer must address ALL of the following points using the conventions specified below.\n\nCONVENTIONS:\n- The grid has n rows and m columns, 0-indexed.\n- Cells are processed in column-major order (column 0 top-to-bottom, then column 1 top-to-bottom, etc.).\n- The plug array is 0-indexed with exactly (n+1) entries.\n- Component labels in the plug array are canonicalized by assigning integers 1, 2, 3, ... in left-to-right first-occurrence order.\n\nADDRESS EACH OF THE FOLLOWING:\n\n1. PROFILE STRUCTURE: Define the broken profile as the boundary between processed and unprocessed cells. State the number of plug positions for an n-row grid. Describe the geometric shape of this boundary in terms of horizontal and vertical segments.\n\n2. STATE BOUND: Using Catalan numbers, state the upper bound on the number of distinct canonical plug states for a profile with (n+1) positions. Give the exact numeric value for n = 12.\n\n3. TRANSITION RULES FOR EMPTY CELLS: When processing an empty cell (i, j), define all valid transitions based on the values of the LEFT plug and TOP plug:\n (a) Both LEFT = 0 and TOP = 0\n (b) Exactly one of LEFT or TOP is nonzero\n (c) Both nonzero with different component labels\n (d) Both nonzero with the same component label\n For each case, state what outgoing plug values are produced and any validity constraints.\n\n4. PREMATURE CYCLE REJECTION: Explain what happens in case (d) at a non-terminal cell and why the transition must be handled differently than case (c).\n\n5. COMPONENT MERGING: When two components with different labels are merged in case (c), specify how the plug array is updated and how re-canonicalization is performed.\n\n6. START CELL (0,0): State the valid outgoing plug configuration(s) for the path's starting endpoint. Specify which outgoing plugs may be nonzero and which must be zero, and justify using the degree constraint.\n\n7. END CELL (n-1, m-1): State the required incoming plug configuration for valid Hamiltonian path termination. Specify conditions on LEFT, TOP, and all other plug positions.\n\n8. SPACE MANAGEMENT: Describe how DP states are stored across cell transitions. State how many collections of states must be maintained simultaneously and the resulting space complexity in terms of Catalan numbers.\n\n9. DP RECURRENCE: Write the DP update rule relating dp_next and dp_curr, specifying where canonicalization is applied.\n\n10. TIME AND SPACE COMPLEXITY: State the overall time and space complexity in terms of n, m, and Catalan numbers. Justify feasibility for n = 12, m = 1000 by citing the numeric Catalan bound.\n\nFor verification: on a 3x3 grid with all cells empty, the number of Hamiltonian paths from (0,0) to (2,2) is exactly 2.", "rubrics": [{"criterion": "The response states that the broken profile has exactly n+1 plug positions for an n-row grid, and describes the profile as consisting of n horizontal segments and 1 vertical segment (or equivalently as a staircase or L-shaped boundary).", "weight": 10}, {"criterion": "The response states that the number of distinct canonical plug states is bounded by the Catalan number C_{n+1}, and provides the exact numeric value C_13 = 742900 as the upper bound when n = 12.", "weight": 10}, {"criterion": "The response defines canonicalization as assigning component labels 1, 2, 3, ... in left-to-right first-occurrence order across the plug array, ensuring a unique representation for each distinct connectivity pattern.", "weight": 10}, {"criterion": "The response correctly states that when both LEFT and TOP plugs carry the same component label at a non-terminal cell, the transition must be rejected because it would create a premature cycle, which violates the Hamiltonian path property.", "weight": 15}, {"criterion": "The response specifies that when merging two components with different labels, all occurrences of one label are replaced with the other throughout the plug array, followed by re-canonicalization of the entire state.", "weight": 10}, {"criterion": "The response states that at the start cell (0,0), exactly one outgoing plug is set to a nonzero component label and the other must remain 0, because a path endpoint has degree 1.", "weight": 10}, {"criterion": "The response states that at the end cell (n-1, m-1), exactly one of the two incoming plugs (LEFT or TOP) must be nonzero while the other is 0, AND all remaining plug positions in the array must be exactly 0.", "weight": 15}, {"criterion": "The response provides the DP recurrence as dp_next[canonicalize(new_state)] += dp_curr[old_state] for each valid transition, or an equivalent formulation that explicitly applies canonicalization to the new state before accumulation.", "weight": 5}, {"criterion": "The response states that exactly two DP state collections (current and next) are maintained at any time, and that this achieves space complexity of O(C_{n+1}) rather than storing states for all cells.", "weight": 5}, {"criterion": "The response states the time complexity as O(n * m * C_{n+1}) or an asymptotically equivalent expression, and confirms feasibility for n = 12 and m = 1000 by citing the numeric bound C_13 = 742900.", "weight": 10}], "golden_answer": "1. PROFILE STRUCTURE:\nThe broken profile is the boundary between processed cells (above and to the left of the current cell in column-major order) and unprocessed cells (below and to the right). It forms a staircase or L-shaped boundary consisting of exactly n horizontal segments and 1 vertical segment. The profile has exactly n+1 plug positions for a grid with n rows.\n\n2. STATE BOUND:\nThe number of distinct canonical plug states on (n+1) positions is bounded by the Catalan number C_{n+1}. The Catalan number C_k = (2k)! / ((k+1)! * k!). For n = 12, the profile has 13 positions, so the bound is C_13 = 742,900.\n\n3. TRANSITION RULES FOR EMPTY CELLS:\nWhen processing cell (i, j), let L = LEFT plug value and T = TOP plug value.\n\n(a) L = 0 and T = 0:\nFor an interior cell (not start or end): the cell must have degree 2, so if no segment enters from LEFT or TOP, the only valid choice is to start a new open component at this cell. Create a new component label k and set both outgoing plugs to that label: RIGHT = k and DOWN = k. This means the current cell contributes two incident edges, one to the right and one downward, and those two dangling ends belong to the same component to be connected later.\nFor the start or end cell: degree is 1, so exactly one outgoing plug gets label k, the other stays 0 (see points 6 and 7).\n\n(b) Exactly one of L, T is nonzero (say value = p, the other = 0):\nThe existing segment continues through this cell. Two sub-options for degree-2 cells:\n - Continue RIGHT: set RIGHT plug = p, DOWN plug = 0\n - Continue DOWN: set DOWN plug = p, RIGHT plug = 0\nFor an endpoint cell (degree 1): the segment terminates. Set both outgoing plugs to 0.\n\n(c) Both L and T nonzero with different labels (L = p, T = q, p != q):\nThe cell merges two distinct path segments. Both outgoing plugs become 0 (the cell consumes both incoming segments). The two components must be unified: replace all occurrences of max(p, q) with min(p, q) throughout the plug array, then re-canonicalize (see point 5).\n\n(d) Both L and T nonzero with the same label (L = T = p):\nThis would close a cycle, so it is invalid for a Hamiltonian path and must be rejected. See point 4.\n\n4. PREMATURE CYCLE REJECTION:\nAt any non-terminal cell, if L and T have the same component label, connecting them would join two ends of the same partial component and immediately create a cycle before all cells are finished. That is a premature cycle, so the transition must be rejected.\n\nThe terminal cell is also rejected in case (d), but for the full endpoint condition: using both incoming plugs would give degree 2 at (n-1, m-1), whereas a Hamiltonian path ending there requires degree 1. So valid termination is only the one-incoming-plug case from point 7.\n\n5. COMPONENT MERGING:\nWhen merging labels p and q (assume p < q without loss of generality): scan the entire plug array of (n+1) entries and replace every occurrence of q with p. Then re-canonicalize: scan the array left-to-right and assign new labels 1, 2, 3, ... to each distinct nonzero value in order of first appearance. This ensures the resulting state is in canonical form for hash map lookup.\n\n6. START CELL (0,0):\nCell (0,0) is a path endpoint and must have degree 1. Since it is at position (0,0), there is no LEFT plug and no TOP plug (both are 0 by boundary conditions). The cell must produce exactly one outgoing plug set to component label 1:\n - Option A: RIGHT plug = 1, DOWN plug = 0 (path starts going right)\n - Option B: RIGHT plug = 0, DOWN plug = 1 (path starts going down)\nSetting both to 1 would give degree 2, violating the endpoint constraint.\n\n7. END CELL (n-1, m-1):\nCell (n-1, m-1) is the other path endpoint with degree 1. For a valid Hamiltonian path termination:\n - Exactly one of LEFT or TOP must be nonzero (one incoming segment)\n - The other must be zero\n - All remaining (n-1) plug positions in the array must be exactly 0\nThis ensures that no dangling path segments exist elsewhere in the grid, meaning all free cells have been incorporated into a single path from (0,0) to (n-1, m-1).\n\n8. SPACE MANAGEMENT:\nTwo hash maps (or dictionaries) are maintained: dp_curr (states for the current cell being processed) and dp_next (states being built for the next cell). For each cell, iterate over all entries in dp_curr, compute valid transitions, and accumulate into dp_next. After processing the cell, set dp_curr = dp_next and reset dp_next to empty. This alternation means only O(C_{n+1}) state entries are stored at any time, giving space complexity O(C_{n+1}).\n\n9. DP RECURRENCE:\nFor each state old_state in dp_curr with value dp_curr[old_state]:\n For each valid transition at the current cell producing new_state:\n dp_next[canonicalize(new_state)] += dp_curr[old_state] (mod 10^9 + 7)\n\nHere canonicalize(new_state) relabels the component IDs in the plug array as 1, 2, 3, ... by left-to-right first occurrence, ensuring a unique key for each connectivity pattern.\n\n10. TIME AND SPACE COMPLEXITY:\n- Number of distinct DP states per cell: O(C_{n+1}), bounded by Catalan number C_{n+1}\n- For n = 12: C_13 = 742,900 states\n- Transitions per state per cell: O(1) amortized (constant number of cases, plus O(n) for re-canonicalization, but n <= 12 is treated as constant)\n- Total cells processed: n * m\n- Time complexity: O(n * m * C_{n+1})\n- Space complexity: O(C_{n+1})\n- Feasibility for n = 12, m = 1000: the state cap is C_13 = 742,900, so memory remains bounded by storing at most two such state collections at once. This Catalan bound is the key reason the method is viable for width 12; in practice the number of reachable states is typically well below the worst-case cap.\n\nVERIFICATION:\nFor the 3x3 all-empty grid, the two Hamiltonian paths from (0,0) to (2,2) are:\n Path 1: (0,0) -> (0,1) -> (0,2) -> (1,2) -> (1,1) -> (1,0) -> (2,0) -> (2,1) -> (2,2)\n Path 2: (0,0) -> (1,0) -> (2,0) -> (2,1) -> (1,1) -> (0,1) -> (0,2) -> (1,2) -> (2,2)\nCount = 2."}
{"domain": "Algorithms & Data Structures", "prompt": "You are fighting a vertical column of `n` enemies arranged in a single stack.\n\n- Enemy `1` is at the bottom, enemy `n` is at the top.\n- Enemy `i` starts with health `h[i]`.\n\n### Attack rule\nIn one hit, you may choose **any currently alive enemy** (in any stack that exists at that moment) and reduce its health by `1`.\n\n### Collapse rule after a death\nWhenever an enemy’s health becomes `0` or less, that enemy dies immediately. Then:\n\n1. All enemies that were **above** the dead one fall downward and become a **new stack** (separate from whatever remains below).\n2. In this new stack, the **bottom** enemy takes **fall damage** equal to how many enemies were below it before it fell. \n That number includes the enemy that just died.\n3. If the bottom enemy of the new stack dies from fall damage, the same falling process repeats again for the enemies above it, potentially causing a chain reaction.\n\nThis continues until no newly formed stack has its bottom enemy killed by the fall damage it just received.\n\n### Goal\nDetermine the minimum number of hits required to kill **all** enemies.\n\n---\n\n## Input\nThe input contains multiple test cases.\n\n- The first line contains an integer `t` (`1 ≤ t ≤ 10^4`).\n- For each test case:\n - The first line contains an integer `n` (`2 ≤ n ≤ 2·10^5`) — the number of enemies in the initial stack.\n - The second line contains `n` integers `h[1], h[2], …, h[n]` (`1 ≤ h[i] ≤ 10^9`) — their initial health values.\n\nIt is guaranteed that the sum of `n` over all test cases does not exceed `2·10^5`.\n\n---\n\n## Output\nFor each test case, output one integer: the minimum number of hits needed to eliminate every enemy.", "rubrics": [{"criterion": "Does the answer define dp[i] as the minimum number of attacks needed to eliminate mobs 1 through i?", "weight": 10}, {"criterion": "Does the answer state that the final output for a test case equals dp[n]?", "weight": 10}, {"criterion": "Does the answer state that a mob can receive fall damage at most once?", "weight": 10}, {"criterion": "Does the answer state the base case dp[0] = 0?", "weight": 10}, {"criterion": "Does the answer state the base case dp[1] = h[1]?", "weight": 10}, {"criterion": "Does the answer state that one option makes mob i take exactly 1 fall damage?", "weight": 10}, {"criterion": "Does the answer give the transition term dp[i-1] + max(0, h[i] - 1)?", "weight": 10}, {"criterion": "Does the answer state that the other option makes mob i take exactly i-1 fall damage?", "weight": 10}, {"criterion": "Does the answer give the transition term dp[i-2] + h[i-1] + max(0, h[i] - (i-1))?", "weight": 10}, {"criterion": "Does the answer state a per-test-case time complexity of O(n)?", "weight": 10}], "golden_answer": "### Key observations\n1. **A creature can receive fall damage at most once.** \n After it falls, it becomes the bottom of its new stack, and nothing can later fall “under it” again.\n\n2. **If a creature ever receives fall damage greater than 1,** then the creature directly below it must have been killed by sword hits (not by fall damage). \n Reason: a creature that has already fallen is at the bottom; killing it would only ever make the next creature fall by **1**.\n\n3. Therefore, whenever we want a creature `i` to get a large fall damage amount, we should arrange it so that creature `i-1` is killed **while the original stack below is still intact**, because that maximizes the fall damage to `i` without increasing the number of sword hits needed elsewhere.\n\n---\n\n### DP definition\nLet `dp[i]` be the minimum number of sword hits needed to eliminate creatures `1..i` (from the bottom up, considering only these `i` creatures).\n\nBase:\n- `dp[0] = 0`\n- `dp[1] = h[1]`\n\nFor `i ≥ 2`, we consider two ways to handle creature `i`:\n\n---\n\n### Option A: creature `i` only falls by 1\nIf creature `i-1` dies when it is the bottom of the current stack containing `i-1` and `i`, then `i` falls and takes **1** damage.\n\nCost:\n- clear `1..i-1`: `dp[i-1]`\n- finish creature `i` after 1 fall damage: `max(0, h[i] - 1)`\n\nSo:\n\\[\n\\text{costA} = dp[i-1] + \\max(0, h[i] - 1)\n\\]\n\n---\n\n### Option B: creature `i` gets maximum fall damage `(i-1)`\nKill creature `i-1` directly **before** removing any of `1..i-2`, so creature `i` falls from the original height and takes `(i-1)` damage.\n\nCost:\n- clear `1..i-2` eventually: `dp[i-2]`\n- kill creature `i-1` by hits: `h[i-1]`\n- finish creature `i` after `(i-1)` fall damage: `max(0, h[i] - (i-1))`\n\nSo:\n\\[\n\\text{costB} = dp[i-2] + h[i-1] + \\max(0, h[i] - (i-1))\n\\]\n\n---\n\n### Transition and answer\n\\[\ndp[i] = \\min(\\text{costA}, \\text{costB})\n\\]\nThe required minimum hits for the full stack is `dp[n]`.\n\n---\n\n### Complexity\nEach `dp[i]` is computed in `O(1)`, so the solution is `O(n)` per test case (and `O(\\sum n)` overall)."}
{"domain": "Algorithms & Data Structures", "prompt": "You are given a tree with `n` nodes. Node `i` has an allowed initial value interval `[l_i, r_i]`.\nYou choose initial values `a_i` such that:\n`l_i ≤ a_i ≤ r_i`\n\nA tree is **balanced** if all node values are equal; the balanced value is that common value.\n\n**Operation:** choose two nodes `u` and `v`. Consider the tree rooted at `u`. Increase by `1` the values of all nodes in the subtree of `v` (in that rooting). You may choose `u = v`. Values can only increase.\n\nFind the **minimum possible** final balanced value after any number of operations.\n\n### Input\n- `n` (`1 ≤ n ≤ 2·10^5`)\n- `n` lines: `l_i, r_i` (`0 ≤ l_i ≤ r_i ≤ 10^9`)\n- `n-1` edges forming a tree\n\n### Output\nOne integer: the minimum achievable balanced value.", "rubrics": [{"criterion": "Does the answer state that for an edge between parent p and child v (in a chosen rooting), choosing (u=p,v=v) increases (a_v−a_p) by 1 and choosing (u=v,v=p) decreases (a_v−a_p) by 1 (i.e., one operation changes the edge difference by exactly ±1)?", "weight": 10}, {"criterion": "Does the answer state that for fixed initial values a, making a_v = a_p on an edge (p,v) requires exactly |a_v−a_p| operations affecting that edge (because each such operation changes the difference by 1)?", "weight": 10}, {"criterion": "Does the answer give the final balanced value for a fixed rooting at 1 as F = a_1 + sum_{v≠1}?", "weight": 10}, {"criterion": "Does the answer define the bottom-up choice of initial values as a_v = min(r_v, max(l_v, max_{child u of v}))?", "weight": 10}, {"criterion": "Does the answer justify that if r_v allows a_v ≥ max_child, then choosing a_v below max_child cannot improve the objective (it only increases required increments on edges to children)?", "weight": 10}, {"criterion": "Does the answer explicitly handle the clipped case: if r_v < max_child, then a_v is set to r_v and the deficit (max_child − r_v) is necessarily paid later via the term max(0, a_child − a_v)?", "weight": 10}, {"criterion": "Does the answer describe computing the chosen a_v values using a postorder DFS from root 1 (children processed before parent)?", "weight": 10}, {"criterion": "Does the answer describe computing the final answer by accumulating sum_{v≠1}?", "weight": 10}, {"criterion": "Does the answer state an implementation complexity of O(n) time and O(n) memory and mention using 64-bit integers for the answer?", "weight": 10}], "golden_answer": "### Expert Solution\n\nRoot the tree at node `1`. Let `p(v)` be the parent of `v`.\n\n---\n\n### A) Final balanced value for fixed initial values `a`\n\nConsider an edge `(p, v)`.\n\nAn operation “increment subtree of `v` when rooted at `u`” can be used in two relevant ways for this edge:\n\n- Choose `u = p`, `v = v`: increments the `v`-side component, so `(a_v - a_p)` **increases by 1**.\n- Choose `u = v`, `v = p`: increments the `p`-side component (the side containing node `1`), so `(a_v - a_p)` **decreases by 1**.\n\nSo each operation changes the edge difference by exactly `±1`, hence equalizing the edge requires exactly `|a_v - a_p|` operations affecting it.\n\nIf `a_v > a_p`, to make them equal we must decrease `(a_v - a_p)` to `0`, which forces incrementing the **root side** exactly `a_v - a_p` times, increasing the final common value by that amount.\nIf `a_v ≤ a_p`, we can equalize by incrementing only the `v`-side, which does **not** increase the root-side final value.\n\nTherefore the final balanced value (with root fixed at `1`) is:\n`F(a) = a_1 + ∑_{v ≠ 1} max(0, a_v - a_{p(v)})`\n\n---\n\n### B) Optimal choice of initial values `a_v ∈ [l_v, r_v]`\n\nCompute `a` bottom-up. For node `v`, let\n`M_v = max_{u child of v} a_u`\n(with `M_v = -∞` for a leaf).\n\nIf `r_v` allows `a_v ≥ M_v`, choosing `a_v < M_v` only increases the required increments on edges to children (since some child would exceed `v` more), so it cannot reduce `F(a)`. Thus we pick:\n`a_v = min(r_v, max(l_v, M_v))`\n\nIf `r_v < M_v`, we are forced to set `a_v = r_v`; the unavoidable deficit is then paid later via terms `max(0, a_u - a_v)` for the too-large children.\n\n---\n\n### Algorithm\n\n1. Root at `1` and run a postorder DFS to compute\n `a_v = min(r_v, max(l_v, max_{child} a_{child}))`\n\n2. Compute\n `ans = a_1 + ∑_{v ≠ 1} max(0, a_v - a_{p(v)})`\n\nUse 64-bit integers.\n\n---\n\n### Complexity\n\n`O(n) time`, `O(n) memory`\nwhich fits `n ≤ 2·10^5`."}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem: Eliminate “+1 Later” Conflicts\n\nYou are given an integer sequence `a` of length `n`. Call a sequence `b` **valid** if there are **no** positions `i < j` such that:\n\n\\[\nb_j = b_i + 1\n\\]\n\nIn other words, you must avoid any situation where a value appears and **somewhere later** a value exactly **one larger** appears.\n\nYou may delete elements from `a` (keeping the remaining elements in their original order). Your task is to compute the **minimum number of deletions** required so that the remaining sequence becomes valid.\n\n---\n\n## Input\nThe input contains multiple test cases.\n\n- The first line contains an integer `t` (`1 ≤ t ≤ 6·10^4`) — the number of test cases.\n- For each test case:\n - The first line contains an integer `n` (`1 ≤ n ≤ 3·10^5`) — the length of the sequence.\n - The second line contains `n` integers `a1, a2, …, an` (`1 ≤ ai ≤ n`).\n\nIt is guaranteed that the sum of `n` over all test cases does not exceed `3·10^5`.\n\n---\n\n## Output\nFor each test case, output one integer: the minimum number of elements that must be removed from `a` so that the remaining sequence is valid.\n", "rubrics": [{"criterion": "Does the answer state the forbidden pattern as existence of indices i<j with b[j] = b[i] + 1?", "weight": 1}, {"criterion": "Does the answer sort the pair list by value in non-decreasing order?", "weight": 1}, {"criterion": "Does the answer define dp[i] as the maximum size of a good selection whose last chosen pair is the i-th pair in the sorted list?", "weight": 1}, {"criterion": "Does the answer include a maintained maximum over dp[j] for processed pairs satisfying value[j] ≤ value[i] − 2?", "weight": 1}, {"criterion": "Does the answer include a query for the maximum dp among processed pairs satisfying (value = current value − 1, position > current position)?", "weight": 1}, {"criterion": "Does the answer state that the final result equals n minus the maximum attainable kept length (answer = n − keep)?", "weight": 1}, {"criterion": "Does the answer construct a list of pairs (a[i], i) using the original index as the second component?", "weight": 1}, {"criterion": "Does the answer specify that equal values are tie-broken by sorting indices in non-increasing (descending) order?", "weight": 1}, {"criterion": "Does the answer specify the disallowed transition condition (value[i] = value[j] + 1, pos[i] > pos[j])?", "weight": 1}, {"criterion": "Does the answer include a maintained maximum dp among processed pairs with value equal to the current value?", "weight": 1}], "golden_answer": "### Key reformulation\nWe want to keep as many elements as possible. Let `keep` be the maximum size of a subsequence that is **good**; then the answer is:\n\n\\[\n\\text{removed} = n - keep\n\\]\n\nA subsequence is **not good** exactly when it contains two chosen indices `p<q` with `a[q]=a[p]+1`.\nSo, if we choose some elements of value `x` and some of value `x+1`, then **every chosen `(x+1)` must lie strictly to the left of every chosen `x`**.\n\n---\n\n### Step 1: Sort values with positions\nCreate pairs `(value, position)` for all indices.\n\nSort these pairs by:\n1. `value` increasing\n2. `position` decreasing for equal values\n\nCall the sorted list `v[1..n]`, where `v[i] = (val[i], pos[i])`.\n\nThis tie-break (positions descending inside equal values) will let us treat “taking multiple equal values” cleanly while enforcing constraints only between consecutive values.\n\n---\n\n### Step 2: DP definition\nDefine:\n\n- `dp[i]` = maximum number of kept elements in a good subsequence **whose last selected pair is exactly** `v[i]`.\n\nThen:\n\n\\[\ndp[i] = 1 + \\max dp[j]\n\\]\nover all `j < i` that can precede `i` without creating a forbidden `(+1 later)` pair.\n\nWhen is transition `j -> i` invalid?\n- It is invalid only in the specific case:\n - `val[i] = val[j] + 1` **and**\n - `pos[i] > pos[j]`\n \nBecause that would mean an element of value `val[j]` occurs earlier in the kept subsequence and a `+1` occurs later, which is forbidden.\n\nSo the transition is allowed iff:\n\n\\[\nval[i] \\ne val[j] + 1 \\quad \\text{or} \\quad pos[i] < pos[j]\n\\]\n\nFinally:\n\n\\[\nkeep = \\max_{1 \\le i \\le n} dp[i], \n\\quad \\text{answer} = n - keep\n\\]\n\n---\n\n### Step 3: Speeding up the transition\nA direct computation is `O(n^2)`, too slow. We optimize by splitting candidates `j` into three disjoint groups:\n\n#### A) Values at most `val[i]-2`\nIf `val[j] <= val[i]-2`, then `val[i]` cannot equal `val[j]+1`, so the transition is always valid.\n\nMaintain:\n- `bestSmall` = maximum `dp[j]` among all processed `j` with `val[j] <= currentValue-2`.\n\n#### B) Same value: `val[j] = val[i]`\nAlways valid (since the forbidden condition requires `+1` difference).\n\nMaintain:\n- `bestSame[value]` = maximum `dp[j]` seen so far for this exact value.\n\n#### C) Previous value: `val[j] = val[i]-1`\nThis is the only case where position matters. We need `pos[i] < pos[j]`.\n\nInside each value group, positions are processed in **decreasing** order (because of the sort).\nSo for value `val[i]-1`, we can maintain a structure that answers:\n- maximum `dp[j]` among those earlier in the group with `pos[j] > pos[i]`\n\nThis can be done with a running **suffix maximum over the group** (equivalently: as you sweep positions downward, maintain the best dp seen so far).\n\nCall this query result:\n- `bestPrevGreaterPos`\n\nThen:\n\n\\[\ndp[i] = 1 + \\max\\big(bestSmall,\\; bestSame[val[i]],\\; bestPrevGreaterPos\\big)\n\\]\n\nAfter computing `dp[i]`, update the maintained maxima for future steps.\n\n---\n\n### Complexity\n- Sorting pairs: `O(n log n)` per test file (overall across test cases).\n- DP with maintained maxima: `O(n)` after sorting.\n- Total across all tests: `O((\\sum n)\\log(\\sum n))`, with `\\sum n \\le 3\\cdot 10^5`.\n\nThis meets the constraints.\n\n---\n"}
{"domain": "Programming Languages, Compilers & Formal Methods", "prompt": "You are given a linear scan register allocation problem with 3 physical registers: R0, R1, R2.\n\nLive intervals for virtual registers:\n\nV0: [0,7]\nV1: [1,5]\nV2: [2,9]\nV3: [3,6]\nV4: [4,11]\nV5: [6,10]\nV6: [8,14]\nV7: [10,13]\nV8: [12,15]\nV9: [1,3]\n\nUse the following deterministic rules:\n\n1. Process intervals in ascending order of start point.\n2. If two intervals have the same start point, process the one with the smaller end point first.\n3. Before processing an interval with start point `s`, expire every active interval whose end point is less than or equal to `s`.\n4. If one or more registers are free, assign the lowest-numbered free register.\n5. If all registers are occupied:\n - Consider the active intervals plus the new interval.\n - Spill the interval with the largest end point.\n - If multiple intervals tie for the largest end point, spill the new interval.\n - If the new interval is spilled, it receives no register.\n - Otherwise, remove the spilled active interval and give its register to the new interval.\n6. Record spill events in the exact order they occur.\n7. For part C, evaluate the active-set size only at the distinct start indices that appear in the input: `0, 1, 2, 3, 4, 6, 8, 10, 12`.\n - At each such index, first finish processing all intervals that start there.\n - Then measure the number of active intervals.\n\nTasks:\n\nA. List the intervals in the exact processing order.\n\nB. List the spill events in order.\n\nC. List all start indices from `0, 1, 2, 3, 4, 6, 8, 10, 12` where the number of active intervals is exactly 3 after all intervals starting at that index have been processed.\n\nD. Provide the final register assignment for every interval that is not spilled.\n\nUse this exact output format:\n\nProcessing Order: comma-separated interval names\nSpill Events: comma-separated interval names, or `None` if there are no spills\nActive Count 3 At: comma-separated start indices\nFinal Register Assignments:\none `interval -> register` entry per line, ordered by interval name\n", "rubrics": [{"criterion": "Lists the processing order exactly as V0, V9, V1, V2, V3, V4, V5, V6, V7, V8.", "weight": 15}, {"criterion": "States that the total number of spill events is exactly 2.", "weight": 10}, {"criterion": "Identifies the first spill event as V2.", "weight": 10}, {"criterion": "Identifies the second spill event as V4.", "weight": 10}, {"criterion": "Lists the part C indices exactly as 1, 2, 3, 4, 12 with no missing or extra indices.", "weight": 20}, {"criterion": "Gives the R0 final assignments exactly as V0 -> R0 and V6 -> R0.", "weight": 10}, {"criterion": "Gives the R1 final assignments exactly as V3 -> R1, V5 -> R1, V7 -> R1, and V9 -> R1.", "weight": 15}, {"criterion": "Gives the R2 final assignments exactly as V1 -> R2 and V8 -> R2.", "weight": 10}], "golden_answer": "Processing Order: V0, V9, V1, V2, V3, V4, V5, V6, V7, V8\nSpill Events: V2, V4\nActive Count 3 At: 1, 2, 3, 4, 12\nFinal Register Assignments:\nV0 -> R0\nV1 -> R2\nV3 -> R1\nV5 -> R1\nV6 -> R0\nV7 -> R1\nV8 -> R2\nV9 -> R1\n\nExplanation\n\nStep 1: Determine processing order\n\nIntervals are sorted by increasing start point, and ties are broken by smaller end point first.\n\n- Start 0: V0\n- Start 1: V9 before V1 because 3 < 5\n- Start 2: V2\n- Start 3: V3\n- Start 4: V4\n- Start 6: V5\n- Start 8: V6\n- Start 10: V7\n- Start 12: V8\n\nSo the exact processing order is:\nV0, V9, V1, V2, V3, V4, V5, V6, V7, V8\n\nStep 2: Simulate the allocator\n\nStart with no active intervals and all registers free.\n\n1. Process V0 = [0,7]\n- Expire intervals with end <= 0: none\n- Lowest free register is R0\n- Assign V0 -> R0\n- Active set: V0(R0)\n\n2. Process V9 = [1,3]\n- Expire intervals with end <= 1: none\n- Lowest free register is R1\n- Assign V9 -> R1\n- Active set: V0(R0), V9(R1)\n\n3. Process V1 = [1,5]\n- Expire intervals with end <= 1: none\n- Lowest free register is R2\n- Assign V1 -> R2\n- Active set: V0(R0), V9(R1), V1(R2)\n\n4. Process V2 = [2,9]\n- Expire intervals with end <= 2: none\n- No free register exists\n- Compare end points of V0(7), V9(3), V1(5), V2(9)\n- Largest end point is 9, so spill V2\n- V2 gets no register\n- Active set stays: V0(R0), V9(R1), V1(R2)\n\n5. Process V3 = [3,6]\n- Expire intervals with end <= 3: V9 expires, so R1 becomes free\n- Lowest free register is R1\n- Assign V3 -> R1\n- Active set: V0(R0), V1(R2), V3(R1)\n\n6. Process V4 = [4,11]\n- Expire intervals with end <= 4: none\n- No free register exists\n- Compare end points of V0(7), V1(5), V3(6), V4(11)\n- Largest end point is 11, so spill V4\n- V4 gets no register\n- Active set stays: V0(R0), V1(R2), V3(R1)\n\n7. Process V5 = [6,10]\n- Expire intervals with end <= 6: V1 expires and V3 expires\n- R2 and R1 are now free\n- Lowest free register is R1\n- Assign V5 -> R1\n- Active set: V0(R0), V5(R1)\n\n8. Process V6 = [8,14]\n- Expire intervals with end <= 8: V0 expires\n- R0 becomes free\n- Lowest free register is R0\n- Assign V6 -> R0\n- Active set: V5(R1), V6(R0)\n\n9. Process V7 = [10,13]\n- Expire intervals with end <= 10: V5 expires\n- R1 becomes free\n- Lowest free register is R1\n- Assign V7 -> R1\n- Active set: V6(R0), V7(R1)\n\n10. Process V8 = [12,15]\n- Expire intervals with end <= 12: none\n- Lowest free register is R2\n- Assign V8 -> R2\n- Active set: V6(R0), V7(R1), V8(R2)\n\nFrom the full trace, the spill events occur in this exact order:\nV2, V4\n\nStep 3: Compute part C exactly\n\nPart C asks for the distinct start indices from the prompt, after all intervals beginning at that index have been processed.\n\n- At start 0: active set is {V0} -> size 1\n- At start 1: after processing both V9 and V1, active set is {V0, V9, V1} -> size 3\n- At start 2: after processing V2 and spilling it, active set is still {V0, V9, V1} -> size 3\n- At start 3: after expiring V9 and assigning V3, active set is {V0, V1, V3} -> size 3\n- At start 4: after processing V4 and spilling it, active set is still {V0, V1, V3} -> size 3\n- At start 6: active set is {V0, V5} -> size 2\n- At start 8: active set is {V5, V6} -> size 2\n- At start 10: active set is {V6, V7} -> size 2\n- At start 12: active set is {V6, V7, V8} -> size 3\n\nTherefore the exact indices for part C are:\n1, 2, 3, 4, 12\n\nStep 4: Final register assignments\n\nOnly non-spilled intervals appear in the final assignment list. Reading them from the simulation:\n\n- V0 -> R0\n- V1 -> R2\n- V3 -> R1\n- V5 -> R1\n- V6 -> R0\n- V7 -> R1\n- V8 -> R2\n- V9 -> R1\n\nSpilled intervals:\nV2, V4\n"}
{"domain": "Algorithms & Data Structures", "prompt": "Steve is trapped in a tunnel filled with hostile creepers. There are n creepers standing in a straight line, indexed from 1 to n.\n\nFor each position i, the creeper at that position has an explosive power e_i.\nWe use the term “creepers” consistently throughout; all entities referred to are the same.\n\nExplosion Rule:\nIf Steve detonates the creeper at position i, it explodes and kills every creeper at position j such that:\n|i − j| < e_i\n\nThis condition is strict. Positions where |i − j| = e_i are NOT affected.\nEquivalently, detonating creeper i kills exactly the creepers in the interval:\n[i − e_i + 1, i + e_i − 1], inclusive.\n\nIf e_i = 0, the interval is empty, meaning such a creeper cannot be detonated at all.\nDead creepers cannot be detonated again.\n\nObjective:\nSteve must kill all creepers using as few detonations as possible.\n\nInput:\nEach test contains multiple test cases.\nThe first line contains an integer t, the number of test cases.\n\nFor each test case:\n- The first line contains an integer n (2 ≤ n ≤ 5·10^5), the number of creepers.\n- The second line contains n integers e_1, e_2, …, e_n (0 ≤ e_i ≤ n), where e_i is the explosive power of the i-th creeper.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 5·10^5.\n\nOutput:\nFor each test case:\n- Output −1 if it is impossible to kill all creepers.\n- Otherwise, output:\n 1) An integer k, the minimum number of detonations.\n 2) A sequence of k integers denoting the positions of the creepers to detonate.\n\nIf multiple valid solutions exist, any one may be printed.\n\nWorked Example (Explosion Mechanics):\n\nIf n = 7 and e = [0, 2, 0, 3, 0, 0, 0]:\n\nDetonating creeper at position 4 (e_4 = 3) kills creepers at positions:\n|4 − j| < 3 → j ∈ {2, 3, 4, 5, 6}\n\nSo the affected interval is [2, 6].\n", "rubrics": [{"criterion": "Does the answer explicitly define the detonation interval of creeper i as [i − e_i + 1, i + e_i − 1]?", "weight": 10}, {"criterion": "Does the answer state that two creepers cannot both be detonated if one lies inside the other’s detonation interval ?", "weight": 10}, {"criterion": "Does the answer define dp[i] as the minimum detonations needed to kill all creepers up to position (i + e_i − 1) with creeper i being the rightmost detonated creeper?", "weight": 10}, {"criterion": "Does the answer list Case 1 transition conditions exactly as j + e_j − 1 < i and i − e_i + 1 ≤ j + e_j?", "weight": 10}, {"criterion": "Does the answer list Case 2 transition conditions exactly as j < i − e_i + 1 and i − e_i + 1 ≤ j + e_j?", "weight": 10}, {"criterion": "Does the answer state that dp[i] is computed using exactly two range minimum queries: [i − e_i, i − 1] and [i − e_i, i + e_i − 1]?", "weight": 10}, {"criterion": "Does the answer state the dp formula dp[i] = 1 + min(query1, query2)?", "weight": 10}, {"criterion": "Does the answer specify the exact point update rule segtree[i + e_i − 1] = min(current value, dp[i]) after computing dp[i]?", "weight": 10}, {"criterion": "Does the answer state that the final result equals min(dp[i]) over all i satisfying i + e_i − 1 ≥ n, and outputs −1 if no finite dp[i] exists?", "weight": 10}, {"criterion": "Does the answer state that reconstruction uses predecessor tracking and detonates the selected creepers in increasing order of explosive power e_i?", "weight": 10}], "golden_answer": "Notation:\nWe use e_i to denote the explosive power of the creeper at position i, exactly as defined in the task prompt.\n\nDetonation Interval:\nDetonating creeper i kills all creepers in the interval:\n[i − e_i + 1, i + e_i − 1]\n\nTwo creepers cannot both be detonated if their detonation intervals overlap in a way that one would destroy the other before it is detonated.\n\nDynamic Programming Definition:\n\nDefine:\ndp[i] = the minimum number of detonations required to kill all creepers up to position (i + e_i − 1),\nwith creeper i being the rightmost detonated creeper.\n\nExact Transition Conditions:\n\nFor a transition from a previously detonated creeper j < i to creeper i, exactly two valid cases exist.\n\nCase 1: Creeper i is strictly to the right of j’s detonation interval\nj + e_j − 1 < i\ni − e_i + 1 ≤ j + e_j\n\nCase 2: Creeper j is strictly to the left of i’s detonation interval\nj < i − e_i + 1\ni − e_i + 1 ≤ j + e_j\n\nSegment Tree Optimization:\n\nA naive implementation of these transitions is O(n²).\nTo optimize, process creepers from left to right and maintain a segment tree where:\nsegtree[x] stores the minimum detonations needed to kill all creepers up to position x.\nAll values are initialized to infinity.\n\nExact Computation of dp[i]:\n\nWhen processing creeper i, compute dp[i] using exactly two range minimum queries:\n\n1) Range [i − e_i, i − 1]\n2) Range [i − e_i, i + e_i − 1]\n\nThen:\ndp[i] = 1 + min(result of both queries)\n\nExact Point Update:\n\nAfter computing dp[i], update:\nsegtree[i + e_i − 1] = min(current value, dp[i])\n\nFinal Answer:\n\nThe minimum number of detonations required is:\nmin over all i such that i + e_i − 1 ≥ n of dp[i]\n\nIf no such i exists with a finite dp[i], output −1.\n\nReconstruction and Order:\n\nStore predecessor information during DP to reconstruct the detonated creepers.\nDetonate the chosen creepers in increasing order of explosive power e_i to ensure no detonation kills a later one.\n\nComplexity:\nTime Complexity: O(n log n)\nSpace Complexity: O(n)\n"}
{"domain": "Algorithms & Data Structures", "prompt": "# Odd-Quorum Rewrite Maximization — Extended Deterministic Output\n\nYou are given `t` test cases. In each test case:\n- an array `a` of `n` **positive integers**\n- a positive integer `k`\n\nYou may apply a \"rewrite\" operation that overwrites selected elements by a median.\n\n---\n\n## Rewrite game (per test case)\n\n1. Choose one **odd** integer `x` with `1 ≤ x ≤ n`. This `x` is fixed for the entire test case.\n2. You may perform the following operation **at most `k` times** (possibly zero), always using the same chosen `x`:\n - Choose any subsequence of the **current** array of length exactly `x` (indices strictly increasing).\n - Let `m` be the median of those `x` values (for odd `x`, median is the `((x+1)/2)`-th smallest).\n - Overwrite all `x` chosen positions with the value `m`.\n\nYour objective is to maximize the final sum `sum(a[i])`.\n\n---\n\n## Worked example\n\nConsider `a = [1, 5, 3, 2, 8]`, `n = 5`, `k = 1`.\n\n**Step 1 — Sort and build prefix sums.**\nSorted: `b = [1, 2, 3, 5, 8]`. Prefix sums: `p = [0, 1, 3, 6, 11, 19]`. Base sum `S = 19`.\n\n**Step 2 — Write the gain formula.**\nWrite `x = 2y + 1`. For median at sorted position `i` with half-window `y`:\n- `L = min(k·y, i−1)` elements below `b[i]` get raised to `b[i]`.\n- `y` elements `b[i+1..i+y]` are consumed (pulled down to `b[i]`).\n- `leftGain = L·b[i] − p[L]`\n- `rightLoss = (p[i+y] − p[i]) − y·b[i]`\n- `F(i,y) = S + leftGain − rightLoss`\n\nThe formulation here is guaranteed to be correct for this problem and must be used.\n\n\n**Step 3 — Enumerate all valid `(i, y)` pairs and pick the maximum.**\n\n| i | b[i] | y | x | L | leftGain | rightLoss | F(i,y) |\n|---|------|---|---|---|----------|-----------|--------|\n| 4 | 5 | 1 | 3 | min(1,3)=1 | 1·5−1=4 | (11−6)−1·5=0 | 19+4−0=**23** |\n| 5 | 8 | 0 | 1 | 0 | 0 | 0 | 19 |\n| 3 | 3 | 1 | 3 | 1 | 3−1=2 | (11−6)−3=2 | 19 |\n| 3 | 3 | 2 | 5 | 2 | 6−3=3 | (19−6)−6=7 | 15 |\n| 2 | 2 | 1 | 3 | 1 | 2−1=1 | (6−3)−2=1 | 19 |\n\nWait — let me recompute `(i=4, y=1)`:\n- `rightLoss = p[5]−p[4] − 1·5 = 19−11 − 5 = 3`\n- `F = 19 + 4 − 3 = 20`\n\nThe maximum is `F(4,1) = 20` with `x=3`, median `b[4]=5`, `L=1`.\n\nInterpretation on the sorted array: the `L=1` smallest value (`b[1]=1`) is raised to `5` (gain = 4), and the `y=1` value just above the median (`b[5]=8`) is pulled down to `5` (loss = 3). Net change = +1, new sum = 20.\n\n---\n\n## Deterministic reporting requirements\n\nFor each test case `c ∈ {1,2,3,4,5}`, you must output:\n- `baseSum_c`: the initial sum of the given array\n- `bestSum_c`: the maximum achievable final sum\n- `gain_c`: `bestSum_c - baseSum_c`\n- `bestX_c`: the odd `x` used by an optimal strategy\n- `bestMedian_c`: the median value used by an optimal strategy\n- `bestI_c`: the 1-indexed position `i` of `bestMedian_c` in the **sorted** array `b` (defined below), chosen by tie-break\n- `bestL_c`: the value `L = min(k*y, i-1)` for the chosen optimum where `x = 2y+1`\n\n### Sorting convention (for `bestI_c`)\n\nLet `b` be `a` sorted in nondecreasing order (1-indexed: `b[1]..b[n]`).\n\n### Tie-break rule (to make the answer unique)\n\nAmong all strategies achieving `bestSum_c`, pick the one with:\n1. smallest `x`\n2. then smallest `bestMedian`\n3. then smallest `bestI` (in the sorted array)\n\n---\n\n## Required global outputs\n\nAlso output:\n- `totalBaseSum`: sum of all `baseSum_c`\n- `totalBestSum`: sum of all `bestSum_c`\n- `totalGain`: `totalBestSum - totalBaseSum`\n\nAnd output these complexity strings **exactly**:\n- `perTestTime = \"O(n log n)\"`\n- `totalTime = \"O(S log S)\"` where `S = Σn` over all test cases\n- `extraSpace = \"O(n)\"` (extra space per test case, excluding input storage)\n\n---\n\n## Output format\n\n\nYour final answer must include **one** JSON object containing **all** keys described above.\nAdditional explanations are allowed, but the JSON object must be clearly present and valid.\n\nAll `*_Sum_*`, `gain_*`, `bestX_*`, `bestMedian_*`, `bestI_*`, `bestL_*` must be integers.\nAll complexity values must be strings exactly as specified.\n\n---\n\n## Fixed input in this prompt\n\n`t = 5`\n\n### Test case 1\n- `n = 12`, `k = 2`\n- `a = [9, 1, 3, 50, 2, 10, 2, 11, 4, 10, 100, 3]`\n\n### Test case 2\n- `n = 9`, `k = 1`\n- `a = [54, 1, 53, 1, 52, 100, 1, 51, 50]`\n\n### Test case 3\n- `n = 13`, `k = 3`\n- `a = [2, 31, 150, 2, 33, 34, 30, 2, 151, 32, 100, 2, 2]`\n\n### Test case 4\n- `n = 14`, `k = 2`\n- `a = [3, 21, 3, 20, 3, 22, 21, 20, 3, 101, 3, 100, 20, 3]`\n\n### Test case 5\n- `n = 15`, `k = 3`\n- `a = [2, 45, 2, 91, 40, 2, 43, 44, 46, 1, 42, 90, 41, 2, 2]`", "rubrics": [{"criterion": "The reasoning contains an exhaustive enumeration of F(i, y) for every valid (i, y) pair in every one of the five test cases, i.e. for each test case and for every i in [1, n] every y in [0, min(i-1, n-i)] is listed together with its computed L, leftGain, rightLoss, and F(i, y) value. A partial enumeration that only shows 'top candidates' must fail this criterion.", "weight": 20}, {"criterion": "The computation path in the reasoning matches the mandated one: for each test case the solver sorts a into b, builds the prefix-sum array p, computes S = p[n], uses x = 2y + 1 with L = min(k*y, i-1), and applies F(i, y) = S + L*b[i] - p[L] - (p[i+y] - p[i]) + y*b[i] (no alternative heuristic or greedy is used).", "weight": 20}, {"criterion": "The tie-break rule is applied correctly and visibly: among all (i, y) pairs that achieve the maximum F in a test case, the solver selects the one with smallest x = 2y+1, then smallest median b[i], then smallest sorted index i, and justifies the choice against the enumeration table.", "weight": 15}, {"criterion": "bestSum_c values are correct for all five test cases: bestSum_1 = 252, bestSum_2 = 507, bestSum_3 = 1030, bestSum_4 = 536, bestSum_5 = 757.", "weight": 20}, {"criterion": "bestX_c values are correct for all five test cases: bestX_1 = 3, bestX_2 = 7, bestX_3 = 5, bestX_4 = 3, bestX_5 = 3.", "weight": 15}, {"criterion": "bestI_c values are correct for all five test cases: bestI_1 = 11, bestI_2 = 5, bestI_3 = 11, bestI_4 = 13, bestI_5 = 14.", "weight": 15}, {"criterion": "bestMedian_c values are correct for all five test cases: bestMedian_1 = 50, bestMedian_2 = 51, bestMedian_3 = 100, bestMedian_4 = 100, bestMedian_5 = 90.", "weight": 10}, {"criterion": "bestL_c values are correct for all five test cases: bestL_1 = 2, bestL_2 = 3, bestL_3 = 6, bestL_4 = 2, bestL_5 = 3.", "weight": 10}, {"criterion": "Global totals are correct and internally consistent: totalBaseSum = 1975, totalBestSum = 3082, totalGain = 1107, every per-test baseSum_c matches sum(a), and every gain_c equals bestSum_c - baseSum_c.", "weight": 10}, {"criterion": "The final answer contains exactly one JSON object with all 38 required keys (baseSum_c, bestSum_c, gain_c, bestX_c, bestMedian_c, bestI_c, bestL_c for c=1..5, plus totalBaseSum, totalBestSum, totalGain, perTestTime, totalTime, extraSpace), numeric fields emitted as JSON integers and complexity fields emitted as the exact strings \"O(n log n)\", \"O(S log S)\", \"O(n)\".", "weight": 10}], "golden_answer": "# Golden Answer\n\n## Approach\n\nWe follow the computation path mandated by the prompt: sort the array, build prefix sums, apply the fixed reduction `F(i, y) = S + L·b[i] - p[L] - (p[i+y] - p[i]) + y·b[i]` with `L = min(k·y, i-1)`, and then **exhaustively enumerate every valid `(i, y)` pair** with `1 ≤ i ≤ n` and `0 ≤ y ≤ min(i-1, n-i)`. After the full table is produced, the tie-break rule (max `F`, then min `x = 2y+1`, then min `b[i]`, then min `i`) picks the unique optimum.\n\nAll five test cases are handled the same way. Tables below show **every** `(i, y)` considered — no candidate is skipped — so the optimum is provably a global maximum over the reduction.\n\n---\n\n### Test case 1: `n=12`, `k=2`, `a = [9, 1, 3, 50, 2, 10, 2, 11, 4, 10, 100, 3]`\n\n- Sorted `b = [1, 2, 2, 3, 3, 4, 9, 10, 10, 11, 50, 100]`\n- Prefix sums `p = [0, 1, 3, 5, 8, 11, 15, 24, 34, 44, 55, 105, 205]`\n- `baseSum_1 = sum(a) = 205` (which equals `S = p[12] = 205`)\n\nFull exhaustive enumeration over every valid `(i, y)` with `0 ≤ y ≤ min(i-1, n-i)`:\n\n| i | b[i] | y | x=2y+1 | L=min(k·y, i-1) | leftGain | rightLoss | F(i,y) |\n|---|------|---|--------|-----------------|----------|-----------|--------|\n| 1 | 1 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 2 | 2 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 2 | 2 | 1 | 3 | 1 | 1 | 0 | 206 |\n| 3 | 2 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 3 | 2 | 1 | 3 | 2 | 1 | 1 | 205 |\n| 3 | 2 | 2 | 5 | 2 | 1 | 2 | 204 |\n| 4 | 3 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 4 | 3 | 1 | 3 | 2 | 3 | 0 | 208 |\n| 4 | 3 | 2 | 5 | 3 | 4 | 1 | 208 |\n| 4 | 3 | 3 | 7 | 3 | 4 | 7 | 202 |\n| 5 | 3 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 5 | 3 | 1 | 3 | 2 | 3 | 1 | 207 |\n| 5 | 3 | 2 | 5 | 4 | 4 | 7 | 202 |\n| 5 | 3 | 3 | 7 | 4 | 4 | 14 | 195 |\n| 5 | 3 | 4 | 9 | 4 | 4 | 21 | 188 |\n| 6 | 4 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 6 | 4 | 1 | 3 | 2 | 5 | 5 | 205 |\n| 6 | 4 | 2 | 5 | 4 | 8 | 11 | 202 |\n| 6 | 4 | 3 | 7 | 5 | 9 | 17 | 197 |\n| 6 | 4 | 4 | 9 | 5 | 9 | 24 | 190 |\n| 6 | 4 | 5 | 11 | 5 | 9 | 70 | 144 |\n| 7 | 9 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 7 | 9 | 1 | 3 | 2 | 15 | 1 | 219 |\n| 7 | 9 | 2 | 5 | 4 | 28 | 2 | 231 |\n| 7 | 9 | 3 | 7 | 6 | 39 | 4 | 240 |\n| 7 | 9 | 4 | 9 | 6 | 39 | 45 | 199 |\n| 7 | 9 | 5 | 11 | 6 | 39 | 136 | 108 |\n| 8 | 10 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 8 | 10 | 1 | 3 | 2 | 17 | 0 | 222 |\n| 8 | 10 | 2 | 5 | 4 | 32 | 1 | 236 |\n| 8 | 10 | 3 | 7 | 6 | 45 | 41 | 209 |\n| 8 | 10 | 4 | 9 | 7 | 46 | 131 | 120 |\n| 9 | 10 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 9 | 10 | 1 | 3 | 2 | 17 | 1 | 221 |\n| 9 | 10 | 2 | 5 | 4 | 32 | 41 | 196 |\n| 9 | 10 | 3 | 7 | 6 | 45 | 131 | 119 |\n| 10 | 11 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 10 | 11 | 1 | 3 | 2 | 19 | 39 | 185 |\n| 10 | 11 | 2 | 5 | 4 | 36 | 128 | 113 |\n| 11 | 50 | 0 | 1 | 0 | 0 | 0 | 205 |\n| 11 | 50 | 1 | 3 | 2 | 97 | 50 | 252 |\n| 12 | 100 | 0 | 1 | 0 | 0 | 0 | 205 |\n\nApplying the tie-break (max F, then min x, then min median, then min i) gives the optimum `(i=11, y=1)` with `F = 252`.\n\n- `baseSum_1 = 205`\n- `bestSum_1 = 252`\n- `gain_1 = 47`\n- `bestX_1 = 3`\n- `bestMedian_1 = 50`\n- `bestI_1 = 11`\n- `bestL_1 = 2`\n\n---\n\n### Test case 2: `n=9`, `k=1`, `a = [54, 1, 53, 1, 52, 100, 1, 51, 50]`\n\n- Sorted `b = [1, 1, 1, 50, 51, 52, 53, 54, 100]`\n- Prefix sums `p = [0, 1, 2, 3, 53, 104, 156, 209, 263, 363]`\n- `baseSum_2 = sum(a) = 363` (which equals `S = p[9] = 363`)\n\nFull exhaustive enumeration over every valid `(i, y)` with `0 ≤ y ≤ min(i-1, n-i)`:\n\n| i | b[i] | y | x=2y+1 | L=min(k·y, i-1) | leftGain | rightLoss | F(i,y) |\n|---|------|---|--------|-----------------|----------|-----------|--------|\n| 1 | 1 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 2 | 1 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 2 | 1 | 1 | 3 | 1 | 0 | 0 | 363 |\n| 3 | 1 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 3 | 1 | 1 | 3 | 1 | 0 | 49 | 314 |\n| 3 | 1 | 2 | 5 | 2 | 0 | 99 | 264 |\n| 4 | 50 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 4 | 50 | 1 | 3 | 1 | 49 | 1 | 411 |\n| 4 | 50 | 2 | 5 | 2 | 98 | 3 | 458 |\n| 4 | 50 | 3 | 7 | 3 | 147 | 6 | 504 |\n| 5 | 51 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 5 | 51 | 1 | 3 | 1 | 50 | 1 | 412 |\n| 5 | 51 | 2 | 5 | 2 | 100 | 3 | 460 |\n| 5 | 51 | 3 | 7 | 3 | 150 | 6 | 507 |\n| 5 | 51 | 4 | 9 | 4 | 151 | 55 | 459 |\n| 6 | 52 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 6 | 52 | 1 | 3 | 1 | 51 | 1 | 413 |\n| 6 | 52 | 2 | 5 | 2 | 102 | 3 | 462 |\n| 6 | 52 | 3 | 7 | 3 | 153 | 51 | 465 |\n| 7 | 53 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 7 | 53 | 1 | 3 | 1 | 52 | 1 | 414 |\n| 7 | 53 | 2 | 5 | 2 | 104 | 48 | 419 |\n| 8 | 54 | 0 | 1 | 0 | 0 | 0 | 363 |\n| 8 | 54 | 1 | 3 | 1 | 53 | 46 | 370 |\n| 9 | 100 | 0 | 1 | 0 | 0 | 0 | 363 |\n\nApplying the tie-break (max F, then min x, then min median, then min i) gives the optimum `(i=5, y=3)` with `F = 507`.\n\n- `baseSum_2 = 363`\n- `bestSum_2 = 507`\n- `gain_2 = 144`\n- `bestX_2 = 7`\n- `bestMedian_2 = 51`\n- `bestI_2 = 5`\n- `bestL_2 = 3`\n\n---\n\n### Test case 3: `n=13`, `k=3`, `a = [2, 31, 150, 2, 33, 34, 30, 2, 151, 32, 100, 2, 2]`\n\n- Sorted `b = [2, 2, 2, 2, 2, 30, 31, 32, 33, 34, 100, 150, 151]`\n- Prefix sums `p = [0, 2, 4, 6, 8, 10, 40, 71, 103, 136, 170, 270, 420, 571]`\n- `baseSum_3 = sum(a) = 571` (which equals `S = p[13] = 571`)\n\nFull exhaustive enumeration over every valid `(i, y)` with `0 ≤ y ≤ min(i-1, n-i)`:\n\n| i | b[i] | y | x=2y+1 | L=min(k·y, i-1) | leftGain | rightLoss | F(i,y) |\n|---|------|---|--------|-----------------|----------|-----------|--------|\n| 1 | 2 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 2 | 2 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 2 | 2 | 1 | 3 | 1 | 0 | 0 | 571 |\n| 3 | 2 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 3 | 2 | 1 | 3 | 2 | 0 | 0 | 571 |\n| 3 | 2 | 2 | 5 | 2 | 0 | 0 | 571 |\n| 4 | 2 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 4 | 2 | 1 | 3 | 3 | 0 | 0 | 571 |\n| 4 | 2 | 2 | 5 | 3 | 0 | 28 | 543 |\n| 4 | 2 | 3 | 7 | 3 | 0 | 57 | 514 |\n| 5 | 2 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 5 | 2 | 1 | 3 | 3 | 0 | 28 | 543 |\n| 5 | 2 | 2 | 5 | 4 | 0 | 57 | 514 |\n| 5 | 2 | 3 | 7 | 4 | 0 | 87 | 484 |\n| 5 | 2 | 4 | 9 | 4 | 0 | 118 | 453 |\n| 6 | 30 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 6 | 30 | 1 | 3 | 3 | 84 | 1 | 654 |\n| 6 | 30 | 2 | 5 | 5 | 140 | 3 | 708 |\n| 6 | 30 | 3 | 7 | 5 | 140 | 6 | 705 |\n| 6 | 30 | 4 | 9 | 5 | 140 | 10 | 701 |\n| 6 | 30 | 5 | 11 | 5 | 140 | 80 | 631 |\n| 7 | 31 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 7 | 31 | 1 | 3 | 3 | 87 | 1 | 657 |\n| 7 | 31 | 2 | 5 | 6 | 146 | 3 | 714 |\n| 7 | 31 | 3 | 7 | 6 | 146 | 6 | 711 |\n| 7 | 31 | 4 | 9 | 6 | 146 | 75 | 642 |\n| 7 | 31 | 5 | 11 | 6 | 146 | 194 | 523 |\n| 7 | 31 | 6 | 13 | 6 | 146 | 314 | 403 |\n| 8 | 32 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 8 | 32 | 1 | 3 | 3 | 90 | 1 | 660 |\n| 8 | 32 | 2 | 5 | 6 | 152 | 3 | 720 |\n| 8 | 32 | 3 | 7 | 7 | 153 | 71 | 653 |\n| 8 | 32 | 4 | 9 | 7 | 153 | 189 | 535 |\n| 8 | 32 | 5 | 11 | 7 | 153 | 308 | 416 |\n| 9 | 33 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 9 | 33 | 1 | 3 | 3 | 93 | 1 | 663 |\n| 9 | 33 | 2 | 5 | 6 | 158 | 68 | 661 |\n| 9 | 33 | 3 | 7 | 8 | 161 | 185 | 547 |\n| 9 | 33 | 4 | 9 | 8 | 161 | 303 | 429 |\n| 10 | 34 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 10 | 34 | 1 | 3 | 3 | 96 | 66 | 601 |\n| 10 | 34 | 2 | 5 | 6 | 164 | 182 | 553 |\n| 10 | 34 | 3 | 7 | 9 | 170 | 299 | 442 |\n| 11 | 100 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 11 | 100 | 1 | 3 | 3 | 294 | 50 | 815 |\n| 11 | 100 | 2 | 5 | 6 | 560 | 101 | 1030 |\n| 12 | 150 | 0 | 1 | 0 | 0 | 0 | 571 |\n| 12 | 150 | 1 | 3 | 3 | 444 | 1 | 1014 |\n| 13 | 151 | 0 | 1 | 0 | 0 | 0 | 571 |\n\nApplying the tie-break (max F, then min x, then min median, then min i) gives the optimum `(i=11, y=2)` with `F = 1030`.\n\n- `baseSum_3 = 571`\n- `bestSum_3 = 1030`\n- `gain_3 = 459`\n- `bestX_3 = 5`\n- `bestMedian_3 = 100`\n- `bestI_3 = 11`\n- `bestL_3 = 6`\n\n---\n\n### Test case 4: `n=14`, `k=2`, `a = [3, 21, 3, 20, 3, 22, 21, 20, 3, 101, 3, 100, 20, 3]`\n\n- Sorted `b = [3, 3, 3, 3, 3, 3, 20, 20, 20, 21, 21, 22, 100, 101]`\n- Prefix sums `p = [0, 3, 6, 9, 12, 15, 18, 38, 58, 78, 99, 120, 142, 242, 343]`\n- `baseSum_4 = sum(a) = 343` (which equals `S = p[14] = 343`)\n\nFull exhaustive enumeration over every valid `(i, y)` with `0 ≤ y ≤ min(i-1, n-i)`:\n\n| i | b[i] | y | x=2y+1 | L=min(k·y, i-1) | leftGain | rightLoss | F(i,y) |\n|---|------|---|--------|-----------------|----------|-----------|--------|\n| 1 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 2 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 2 | 3 | 1 | 3 | 1 | 0 | 0 | 343 |\n| 3 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 3 | 3 | 1 | 3 | 2 | 0 | 0 | 343 |\n| 3 | 3 | 2 | 5 | 2 | 0 | 0 | 343 |\n| 4 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 4 | 3 | 1 | 3 | 2 | 0 | 0 | 343 |\n| 4 | 3 | 2 | 5 | 3 | 0 | 0 | 343 |\n| 4 | 3 | 3 | 7 | 3 | 0 | 17 | 326 |\n| 5 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 5 | 3 | 1 | 3 | 2 | 0 | 0 | 343 |\n| 5 | 3 | 2 | 5 | 4 | 0 | 17 | 326 |\n| 5 | 3 | 3 | 7 | 4 | 0 | 34 | 309 |\n| 5 | 3 | 4 | 9 | 4 | 0 | 51 | 292 |\n| 6 | 3 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 6 | 3 | 1 | 3 | 2 | 0 | 17 | 326 |\n| 6 | 3 | 2 | 5 | 4 | 0 | 34 | 309 |\n| 6 | 3 | 3 | 7 | 5 | 0 | 51 | 292 |\n| 6 | 3 | 4 | 9 | 5 | 0 | 69 | 274 |\n| 6 | 3 | 5 | 11 | 5 | 0 | 87 | 256 |\n| 7 | 20 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 7 | 20 | 1 | 3 | 2 | 34 | 0 | 377 |\n| 7 | 20 | 2 | 5 | 4 | 68 | 0 | 411 |\n| 7 | 20 | 3 | 7 | 6 | 102 | 1 | 444 |\n| 7 | 20 | 4 | 9 | 6 | 102 | 2 | 443 |\n| 7 | 20 | 5 | 11 | 6 | 102 | 4 | 441 |\n| 7 | 20 | 6 | 13 | 6 | 102 | 84 | 361 |\n| 8 | 20 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 8 | 20 | 1 | 3 | 2 | 34 | 0 | 377 |\n| 8 | 20 | 2 | 5 | 4 | 68 | 1 | 410 |\n| 8 | 20 | 3 | 7 | 6 | 102 | 2 | 443 |\n| 8 | 20 | 4 | 9 | 7 | 102 | 4 | 441 |\n| 8 | 20 | 5 | 11 | 7 | 102 | 84 | 361 |\n| 8 | 20 | 6 | 13 | 7 | 102 | 165 | 280 |\n| 9 | 20 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 9 | 20 | 1 | 3 | 2 | 34 | 1 | 376 |\n| 9 | 20 | 2 | 5 | 4 | 68 | 2 | 409 |\n| 9 | 20 | 3 | 7 | 6 | 102 | 4 | 441 |\n| 9 | 20 | 4 | 9 | 8 | 102 | 84 | 361 |\n| 9 | 20 | 5 | 11 | 8 | 102 | 165 | 280 |\n| 10 | 21 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 10 | 21 | 1 | 3 | 2 | 36 | 0 | 379 |\n| 10 | 21 | 2 | 5 | 4 | 72 | 1 | 414 |\n| 10 | 21 | 3 | 7 | 6 | 108 | 80 | 371 |\n| 10 | 21 | 4 | 9 | 8 | 110 | 160 | 293 |\n| 11 | 21 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 11 | 21 | 1 | 3 | 2 | 36 | 1 | 378 |\n| 11 | 21 | 2 | 5 | 4 | 72 | 80 | 335 |\n| 11 | 21 | 3 | 7 | 6 | 108 | 160 | 291 |\n| 12 | 22 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 12 | 22 | 1 | 3 | 2 | 38 | 78 | 303 |\n| 12 | 22 | 2 | 5 | 4 | 76 | 157 | 262 |\n| 13 | 100 | 0 | 1 | 0 | 0 | 0 | 343 |\n| 13 | 100 | 1 | 3 | 2 | 194 | 1 | 536 |\n| 14 | 101 | 0 | 1 | 0 | 0 | 0 | 343 |\n\nApplying the tie-break (max F, then min x, then min median, then min i) gives the optimum `(i=13, y=1)` with `F = 536`.\n\n- `baseSum_4 = 343`\n- `bestSum_4 = 536`\n- `gain_4 = 193`\n- `bestX_4 = 3`\n- `bestMedian_4 = 100`\n- `bestI_4 = 13`\n- `bestL_4 = 2`\n\n---\n\n### Test case 5: `n=15`, `k=3`, `a = [2, 45, 2, 91, 40, 2, 43, 44, 46, 1, 42, 90, 41, 2, 2]`\n\n- Sorted `b = [1, 2, 2, 2, 2, 2, 40, 41, 42, 43, 44, 45, 46, 90, 91]`\n- Prefix sums `p = [0, 1, 3, 5, 7, 9, 11, 51, 92, 134, 177, 221, 266, 312, 402, 493]`\n- `baseSum_5 = sum(a) = 493` (which equals `S = p[15] = 493`)\n\nFull exhaustive enumeration over every valid `(i, y)` with `0 ≤ y ≤ min(i-1, n-i)`:\n\n| i | b[i] | y | x=2y+1 | L=min(k·y, i-1) | leftGain | rightLoss | F(i,y) |\n|---|------|---|--------|-----------------|----------|-----------|--------|\n| 1 | 1 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 2 | 2 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 2 | 2 | 1 | 3 | 1 | 1 | 0 | 494 |\n| 3 | 2 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 3 | 2 | 1 | 3 | 2 | 1 | 0 | 494 |\n| 3 | 2 | 2 | 5 | 2 | 1 | 0 | 494 |\n| 4 | 2 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 4 | 2 | 1 | 3 | 3 | 1 | 0 | 494 |\n| 4 | 2 | 2 | 5 | 3 | 1 | 0 | 494 |\n| 4 | 2 | 3 | 7 | 3 | 1 | 38 | 456 |\n| 5 | 2 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 5 | 2 | 1 | 3 | 3 | 1 | 0 | 494 |\n| 5 | 2 | 2 | 5 | 4 | 1 | 38 | 456 |\n| 5 | 2 | 3 | 7 | 4 | 1 | 77 | 417 |\n| 5 | 2 | 4 | 9 | 4 | 1 | 117 | 377 |\n| 6 | 2 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 6 | 2 | 1 | 3 | 3 | 1 | 38 | 456 |\n| 6 | 2 | 2 | 5 | 5 | 1 | 77 | 417 |\n| 6 | 2 | 3 | 7 | 5 | 1 | 117 | 377 |\n| 6 | 2 | 4 | 9 | 5 | 1 | 158 | 336 |\n| 6 | 2 | 5 | 11 | 5 | 1 | 200 | 294 |\n| 7 | 40 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 7 | 40 | 1 | 3 | 3 | 115 | 1 | 607 |\n| 7 | 40 | 2 | 5 | 6 | 229 | 3 | 719 |\n| 7 | 40 | 3 | 7 | 6 | 229 | 6 | 716 |\n| 7 | 40 | 4 | 9 | 6 | 229 | 10 | 712 |\n| 7 | 40 | 5 | 11 | 6 | 229 | 15 | 707 |\n| 7 | 40 | 6 | 13 | 6 | 229 | 21 | 701 |\n| 8 | 41 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 8 | 41 | 1 | 3 | 3 | 118 | 1 | 610 |\n| 8 | 41 | 2 | 5 | 6 | 235 | 3 | 725 |\n| 8 | 41 | 3 | 7 | 7 | 236 | 6 | 723 |\n| 8 | 41 | 4 | 9 | 7 | 236 | 10 | 719 |\n| 8 | 41 | 5 | 11 | 7 | 236 | 15 | 714 |\n| 8 | 41 | 6 | 13 | 7 | 236 | 64 | 665 |\n| 8 | 41 | 7 | 15 | 7 | 236 | 114 | 615 |\n| 9 | 42 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 9 | 42 | 1 | 3 | 3 | 121 | 1 | 613 |\n| 9 | 42 | 2 | 5 | 6 | 241 | 3 | 731 |\n| 9 | 42 | 3 | 7 | 8 | 244 | 6 | 731 |\n| 9 | 42 | 4 | 9 | 8 | 244 | 10 | 727 |\n| 9 | 42 | 5 | 11 | 8 | 244 | 58 | 679 |\n| 9 | 42 | 6 | 13 | 8 | 244 | 107 | 630 |\n| 10 | 43 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 10 | 43 | 1 | 3 | 3 | 124 | 1 | 616 |\n| 10 | 43 | 2 | 5 | 6 | 247 | 3 | 737 |\n| 10 | 43 | 3 | 7 | 9 | 253 | 6 | 740 |\n| 10 | 43 | 4 | 9 | 9 | 253 | 53 | 693 |\n| 10 | 43 | 5 | 11 | 9 | 253 | 101 | 645 |\n| 11 | 44 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 11 | 44 | 1 | 3 | 3 | 127 | 1 | 619 |\n| 11 | 44 | 2 | 5 | 6 | 253 | 3 | 743 |\n| 11 | 44 | 3 | 7 | 9 | 262 | 49 | 706 |\n| 11 | 44 | 4 | 9 | 10 | 263 | 96 | 660 |\n| 12 | 45 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 12 | 45 | 1 | 3 | 3 | 130 | 1 | 622 |\n| 12 | 45 | 2 | 5 | 6 | 259 | 46 | 706 |\n| 12 | 45 | 3 | 7 | 9 | 271 | 92 | 672 |\n| 13 | 46 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 13 | 46 | 1 | 3 | 3 | 133 | 44 | 582 |\n| 13 | 46 | 2 | 5 | 6 | 265 | 89 | 669 |\n| 14 | 90 | 0 | 1 | 0 | 0 | 0 | 493 |\n| 14 | 90 | 1 | 3 | 3 | 265 | 1 | 757 |\n| 15 | 91 | 0 | 1 | 0 | 0 | 0 | 493 |\n\nApplying the tie-break (max F, then min x, then min median, then min i) gives the optimum `(i=14, y=1)` with `F = 757`.\n\n- `baseSum_5 = 493`\n- `bestSum_5 = 757`\n- `gain_5 = 264`\n- `bestX_5 = 3`\n- `bestMedian_5 = 90`\n- `bestI_5 = 14`\n- `bestL_5 = 3`\n\n---\n\n\n## Global totals\n\n- `totalBaseSum = 205 + 363 + 571 + 343 + 493 = 1975`\n- `totalBestSum = 252 + 507 + 1030 + 536 + 757 = 3082`\n- `totalGain = 3082 - 1975 = 1107`\n\n## Complexity (as required strings)\n\n- `perTestTime = \"O(n log n)\"` — sorting dominates the asymptotic cost; the prompt pins this string and we report it verbatim.\n- `totalTime = \"O(S log S)\"` where `S = Σ n` across test cases.\n- `extraSpace = \"O(n)\"` — we store only the sorted copy `b` and the prefix-sum array `p`.\n\n## Final JSON\n\n```json\n{\n \"baseSum_1\": 205,\n \"bestSum_1\": 252,\n \"gain_1\": 47,\n \"bestX_1\": 3,\n \"bestMedian_1\": 50,\n \"bestI_1\": 11,\n \"bestL_1\": 2,\n \"baseSum_2\": 363,\n \"bestSum_2\": 507,\n \"gain_2\": 144,\n \"bestX_2\": 7,\n \"bestMedian_2\": 51,\n \"bestI_2\": 5,\n \"bestL_2\": 3,\n \"baseSum_3\": 571,\n \"bestSum_3\": 1030,\n \"gain_3\": 459,\n \"bestX_3\": 5,\n \"bestMedian_3\": 100,\n \"bestI_3\": 11,\n \"bestL_3\": 6,\n \"baseSum_4\": 343,\n \"bestSum_4\": 536,\n \"gain_4\": 193,\n \"bestX_4\": 3,\n \"bestMedian_4\": 100,\n \"bestI_4\": 13,\n \"bestL_4\": 2,\n \"baseSum_5\": 493,\n \"bestSum_5\": 757,\n \"gain_5\": 264,\n \"bestX_5\": 3,\n \"bestMedian_5\": 90,\n \"bestI_5\": 14,\n \"bestL_5\": 3,\n \"totalBaseSum\": 1975,\n \"totalBestSum\": 3082,\n \"totalGain\": 1107,\n \"perTestTime\": \"O(n log n)\",\n \"totalTime\": \"O(S log S)\",\n \"extraSpace\": \"O(n)\"\n}\n```"}
{"domain": "Computer Systems & Operating Systems", "prompt": "# PROMPT\n\nSimulate Tomasulo's Algorithm for out-of-order execution with the following configuration:\n\nEXECUTION LATENCIES (by instruction type):\n- ADD/SUB: 2 cycles\n- MUL: 4 cycles\n- DIV: 8 cycles\n- LOAD: 3 cycles (includes memory access)\n\nRESERVATION STATIONS:\n- 3 Add/Sub stations: Add1, Add2, Add3\n- 2 Mul/Div stations: Mul1, Mul2\n- 2 Load stations: Load1, Load2\n\nThere are no structural hazards on functional units. Every reservation station that is ready to execute can begin execution immediately regardless of how many other stations of the same type are already executing.\n\nREGISTER FILE: F0, F2, F4, F6, F8, F10 (all initially ready with value 0). Integer base registers R1 and R2 are always ready and are not tracked by the algorithm.\n\nRULES:\n1. Issue: One instruction issues per cycle in program order, provided a reservation station of the correct type is available. If no station is available, the instruction stalls and no later instruction can issue.\n2. Execute: Begins the cycle AFTER all source operands are available. An operand broadcast on cycle T is considered available starting cycle T+1.\n3. Write: Results broadcast on the CDB exactly one cycle after execution completes. If execution ends in cycle E, the write occurs in cycle E+1.\n4. CDB Conflict: If multiple instructions are ready to write in the same cycle, the instruction in the station with the lowest name (alphabetical, then numeric) wins. Full priority order: Add1 < Add2 < Add3 < Load1 < Load2 < Mul1 < Mul2.\n5. Stations freed: A reservation station is freed in the same cycle its instruction writes (broadcasts on CDB).\n6. An instruction cannot begin execution in the same cycle it is issued.\n\nINSTRUCTION SEQUENCE (I1-I8):\nI1: LOAD F2, 0(R1)\nI2: LOAD F4, 0(R2)\nI3: MUL F6, F2, F4\nI4: ADD F8, F2, F4\nI5: DIV F10, F6, F2\nI6: SUB F2, F8, F6\nI7: ADD F4, F2, F10\nI8: MUL F2, F4, F6\n\nTrack each instruction through Issue (I), Execute Start (X), Execute End (E), Write (W) cycles.\n\nCompute these EXACT values:\n\n1) In which cycle does I3 (MUL) begin execution?\n2) In which cycle does I5 (DIV) write its result?\n3) What is the SUM of write cycles for all 8 instructions?\n4) In which cycle does I6 (SUB) begin execution?\n5) What is the PRODUCT of issue cycles for I3, I5, and I7?\n6) How many cycles have at least one instruction executing (between execute start and execute end, inclusive)?\n7) In which cycle does I8 write its result?\n8) What is the total number of cycles from I1 issue to I8 write (inclusive)?\n9) What is the SUM of (Write cycle - Issue cycle) for instructions I1 through I4?\n10) In cycle 10, how many reservation stations are occupied?\n\nState each answer with its question number explicitly.\n", "rubrics": [{"criterion": "The response states that I3 (MUL) begins execution in exactly cycle 7.", "weight": 10}, {"criterion": "The response states that I5 (DIV) writes its result in exactly cycle 20.", "weight": 10}, {"criterion": "The response states that the sum of write cycles for all 8 instructions is exactly 116.", "weight": 10}, {"criterion": "The response states that I6 (SUB) begins execution in exactly cycle 12.", "weight": 10}, {"criterion": "The response states that the product of issue cycles for I3, I5, and I7 is exactly 105.", "weight": 10}, {"criterion": "The response states that exactly 22 cycles have at least one instruction executing.", "weight": 10}, {"criterion": "The response states that I8 (MUL) writes its result in exactly cycle 28.", "weight": 10}, {"criterion": "The response states that the total number of cycles from I1 issue to I8 write (inclusive) is exactly 28.", "weight": 10}, {"criterion": "The response states that the sum of (Write cycle - Issue cycle) for I1 through I4 is exactly 21.", "weight": 10}, {"criterion": "The response states that exactly 4 reservation stations are occupied in cycle 10.", "weight": 10}], "golden_answer": "# GOLDEN ANSWER\n\n## Step-by-step Trace\n\n**I1: LOAD F2, 0(R1)** - Issues cycle 1 to Load1. R1 always ready, no data dependency. Cannot execute same cycle as issue (Rule 6), so execution starts cycle 2. Execution latency = 3 cycles: executes cycles 2-4. Writes cycle 5. F2 available from cycle 5 (usable for execution starting cycle 6).\n\n**I2: LOAD F4, 0(R2)** - Issues cycle 2 to Load2. R2 always ready. Execution starts cycle 3 (cycle after issue). Executes cycles 3-5. Writes cycle 6. F4 available from cycle 6 (usable cycle 7).\n\n**I3: MUL F6, F2, F4** - Issues cycle 3 to Mul1. Needs F2 (available cycle 5, usable cycle 6) and F4 (available cycle 6, usable cycle 7). Both operands usable cycle 7. Execution starts cycle 7. Latency = 4: executes cycles 7-10. Writes cycle 11. F6 available from cycle 11 (usable cycle 12).\n\n**I4: ADD F8, F2, F4** - Issues cycle 4 to Add1. Needs F2 (usable cycle 6) and F4 (usable cycle 7). Both usable cycle 7. Execution starts cycle 7. Latency = 2: executes cycles 7-8. Writes cycle 9. (No CDB conflict - only I4 ready to write cycle 9.) F8 available from cycle 9 (usable cycle 10).\n\n**I5: DIV F10, F6, F2** - Issues cycle 5 to Mul2. Needs F6 (usable cycle 12) and F2 (usable cycle 6). Both usable cycle 12. Execution starts cycle 12. Latency = 8: executes cycles 12-19. Writes cycle 20. F10 available from cycle 20 (usable cycle 21).\n\n**I6: SUB F2, F8, F6** - Issues cycle 6 to Add2. Needs F8 (usable cycle 10) and F6 (usable cycle 12). Both usable cycle 12. Execution starts cycle 12. Latency = 2: executes cycles 12-13. Writes cycle 14. (No CDB conflict cycle 14.) F2 (new value) available cycle 14 (usable cycle 15).\n\n**I7: ADD F4, F2, F10** - Issues cycle 7 to Add3. Needs F2 from I6 (usable cycle 15) and F10 from I5 (usable cycle 21). Both usable cycle 21. Execution starts cycle 21. Latency = 2: executes cycles 21-22. Writes cycle 23. F4 available cycle 23 (usable cycle 24).\n\n**I8: MUL F2, F4, F6** - Needs a Mul station. At cycle 8: Mul1 has I3 (executing), Mul2 has I5 (waiting). Both occupied. Stalls cycles 8, 9, 10. Cycle 11: I3 writes and frees Mul1. I8 issues cycle 11 to Mul1. Needs F4 from I7 (usable cycle 24) and F6 (from I3, available cycle 11, usable cycle 12). Both usable cycle 24. Execution starts cycle 24. Latency = 4: executes cycles 24-27. Writes cycle 28.\n\n## Summary Table\n\n| Inst | Station | I | X | E | W |\n|------|---------|----|----|----|----|\n| I1 | Load1 | 1 | 2 | 4 | 5 |\n| I2 | Load2 | 2 | 3 | 5 | 6 |\n| I3 | Mul1 | 3 | 7 | 10 | 11 |\n| I4 | Add1 | 4 | 7 | 8 | 9 |\n| I5 | Mul2 | 5 | 12 | 19 | 20 |\n| I6 | Add2 | 6 | 12 | 13 | 14 |\n| I7 | Add3 | 7 | 21 | 22 | 23 |\n| I8 | Mul1 | 11 | 24 | 27 | 28 |\n\n## Answers\n\n**1)** I3 begins execution in cycle **7**.\n\n**2)** I5 writes its result in cycle **20**.\n\n**3)** Sum of write cycles: 5 + 6 + 11 + 9 + 20 + 14 + 23 + 28 = **116**.\n\n**4)** I6 begins execution in cycle **12**.\n\n**5)** Product of issue cycles for I3, I5, I7: 3 x 5 x 7 = **105**.\n\n**6)** Execution ranges (X to E inclusive): I1: 2-4, I2: 3-5, I3: 7-10, I4: 7-8, I5: 12-19, I6: 12-13, I7: 21-22, I8: 24-27. Union of cycles: {2,3,4,5, 7,8,9,10, 12,13,14,15,16,17,18,19, 21,22, 24,25,26,27} = **22** cycles.\n\n**7)** I8 writes its result in cycle **28**.\n\n**8)** I1 issues cycle 1, I8 writes cycle 28. Total inclusive: 28 - 1 + 1 = **28**.\n\n**9)** (W-I) values: I1: 5-1=4, I2: 6-2=4, I3: 11-3=8, I4: 9-4=5. Sum = 4+4+8+5 = **21**.\n\n**10)** Cycle 10 station occupancy: Mul1 has I3 (executing, writes cycle 11), Mul2 has I5 (waiting, issued cycle 5), Add2 has I6 (waiting, issued cycle 6), Add3 has I7 (waiting, issued cycle 7). Load1 freed cycle 5, Load2 freed cycle 6, Add1 freed cycle 9. I8 not yet issued. Total = **4** stations occupied."}
{"domain": "Algorithms & Data Structures", "prompt": "Construct and analyze the FM-index of a cipher-transformed string.\n\nOriginal: S = \"abracadabra\" (length 11)\n\nCipher at 0-indexed position i, where each character's alphabetic position is p (a=0, b=1, ..., z=25):\n\n- i mod 3 = 0: shift forward by (i mod 5), i.e., new position = (p + (i mod 5)) mod 26\n- i mod 3 = 1: shift backward by ((i * 2) mod 4), i.e., new position = (p - ((i * 2) mod 4)) mod 26\n- i mod 3 = 2: mirror, i.e., new position = 25 - p\n\nApply the cipher to each character of S to obtain T' (length 11), then append '$' to form T = T' + '$' (length 12). All indices are 0-based. The sentinel '$' sorts before all letters.\n\nDefine Occ(c, k) = number of occurrences of character c in BWT[0..k-1] (i.e., the first k characters of BWT).\n\n**Required:**\n\n1. Transform each character of S. For any position where (p - shift) is negative, show the mod 26 computation explicitly. State the final transformed string T.\n\n2. State which characters that appear in S do not appear in T' (the transformed string before appending '$').\n\n3. Construct the suffix array (SA) and Burrows-Wheeler Transform (BWT) of T. List all 12 suffixes in sorted order with their starting positions.\n\n4. Compute the C array (for each character c, the number of characters in T that are lexicographically smaller than c). Then compute: Occ('z', 5), Occ('z', 7), Occ('y', 8), Occ('y', 10).\n\n5. Using LF(i) = C[BWT[i]] + Occ(BWT[i], i), compute LF(3), LF(5), LF(8), LF(11).\n\n6. Perform backward search for the pattern \"ze\". Process characters right-to-left. Show the Occ values used at each step and the resulting SA range.\n\n7. Compute the number of non-empty distinct substrings of T using the LCP array method: n(n+1)/2 - sum(LCP). Identify which consecutive suffix pairs in the sorted order contribute a non-zero LCP value, and state each pair's LCP.", "rubrics": [{"criterion": "The response correctly transforms S = 'abracadabra' to produce T' = 'azidczeyyva' (before appending '$'), yielding T = 'azidczeyyva$'.", "weight": 10}, {"criterion": "The response identifies that the characters 'b' and 'r' from S do not appear in the transformed string T'.", "weight": 5}, {"criterion": "The response produces SA = [11, 10, 0, 4, 3, 6, 2, 9, 8, 7, 5, 1] and BWT = 'av$dizzyyeca'.", "weight": 10}, {"criterion": "The response computes Occ('z', 5) = 0 by counting zero 'z' characters in BWT[0..4] = 'av$di'.", "weight": 5}, {"criterion": "The response computes Occ('z', 7) = 2 by counting two 'z' characters in BWT[0..6] = 'av$dizz'.", "weight": 10}, {"criterion": "The response computes Occ('y', 8) = 1 by counting one 'y' character in BWT[0..7] = 'av$dizzy'.", "weight": 5}, {"criterion": "The response computes Occ('y', 10) = 2 by counting two 'y' characters in BWT[0..9] = 'av$dizzyye'.", "weight": 5}, {"criterion": "The response computes LF(3) = 4.", "weight": 10}, {"criterion": "The response computes LF(5) = 10.", "weight": 10}, {"criterion": "The response computes LF(8) = 9.", "weight": 10}, {"criterion": "The response computes LF(11) = 2.", "weight": 10}, {"criterion": "In backward search for 'ze', the response computes Occ('z', 6) = 1 and derives the final SA range [10, 10].", "weight": 10}, {"criterion": "The response computes the non-empty distinct substring count as 75, using LCP sum = 3 subtracted from 78.", "weight": 10}], "golden_answer": "PHASE 1: CIPHER TRANSFORMATION\n\nOriginal: S = \"abracadabra\" (length 11)\n\nRules:\n- i mod 3 = 0: new_p = (p + (i mod 5)) mod 26\n- i mod 3 = 1: new_p = (p - ((i*2) mod 4)) mod 26\n- i mod 3 = 2: new_p = 25 - p\n\nCharacter-by-character:\n\ni=0: 'a' (p=0) Rule 0: shift = 0 mod 5 = 0. new_p = (0+0) mod 26 = 0 -> 'a'\ni=1: 'b' (p=1) Rule 1: shift = (2) mod 4 = 2. new_p = (1-2) mod 26 = (-1) mod 26 = 25 -> 'z'\n [NEGATIVE: 1-2 = -1; -1 mod 26 = 25]\ni=2: 'r' (p=17) Rule 2: new_p = 25-17 = 8 -> 'i'\ni=3: 'a' (p=0) Rule 0: shift = 3 mod 5 = 3. new_p = (0+3) mod 26 = 3 -> 'd'\ni=4: 'c' (p=2) Rule 1: shift = (8) mod 4 = 0. new_p = (2-0) mod 26 = 2 -> 'c'\ni=5: 'a' (p=0) Rule 2: new_p = 25-0 = 25 -> 'z'\ni=6: 'd' (p=3) Rule 0: shift = 6 mod 5 = 1. new_p = (3+1) mod 26 = 4 -> 'e'\ni=7: 'a' (p=0) Rule 1: shift = (14) mod 4 = 2. new_p = (0-2) mod 26 = (-2) mod 26 = 24 -> 'y'\n [NEGATIVE: 0-2 = -2; -2 mod 26 = 24]\ni=8: 'b' (p=1) Rule 2: new_p = 25-1 = 24 -> 'y'\ni=9: 'r' (p=17) Rule 0: shift = 9 mod 5 = 4. new_p = (17+4) mod 26 = 21 -> 'v'\ni=10: 'a' (p=0) Rule 1: shift = (20) mod 4 = 0. new_p = (0-0) mod 26 = 0 -> 'a'\n\nT' = \"azidczeyyva\"\nT = \"azidczeyyva$\"\n\nPHASE 2: CHARACTERS ELIMINATED FROM S\n\nCharacters in S: {a, b, c, d, r}\nCharacters in T': {a, c, d, e, i, v, y, z}\nMissing: 'b' and 'r' do not appear in T'.\n- 'b' at positions 1 and 8: transformed to 'z' (rule 1) and 'y' (rule 2)\n- 'r' at positions 2 and 9: transformed to 'i' (rule 2) and 'v' (rule 0)\n\nPHASE 3: SUFFIX ARRAY AND BWT\n\nT = \"azidczeyyva$\"\n 0123456789...\n\nSuffixes sorted lexicographically:\n\nSA[0] = 11 | $\nSA[1] = 10 | a$\nSA[2] = 0 | azidczeyyva$\nSA[3] = 4 | czeyyva$\nSA[4] = 3 | dczeyyva$\nSA[5] = 6 | eyyva$\nSA[6] = 2 | idczeyyva$\nSA[7] = 9 | va$\nSA[8] = 8 | yva$\nSA[9] = 7 | yyva$\nSA[10] = 5 | zeyyva$\nSA[11] = 1 | zidczeyyva$\n\nSA = [11, 10, 0, 4, 3, 6, 2, 9, 8, 7, 5, 1]\n\nBWT[i] = T[(SA[i] - 1) mod 12]:\nBWT[0] = T[10] = 'a'\nBWT[1] = T[9] = 'v'\nBWT[2] = T[11] = '$'\nBWT[3] = T[3] = 'd'\nBWT[4] = T[2] = 'i'\nBWT[5] = T[5] = 'z'\nBWT[6] = T[1] = 'z'\nBWT[7] = T[8] = 'y'\nBWT[8] = T[7] = 'y'\nBWT[9] = T[6] = 'e' [TYPO-CHECK: T[6]='e' WRONG -> wait, T=\"azidczeyyva$\", T[6]='e'. Yes correct.]\nBWT[10] = T[4] = 'c' [TYPO-CHECK: T[4]='c'. Yes.]\nBWT[11] = T[0] = 'a'\n\nWAIT - let me recheck T indexing:\nT[0]='a', T[1]='z', T[2]='i', T[3]='d', T[4]='c', T[5]='z', T[6]='e', T[7]='y', T[8]='y', T[9]='v', T[10]='a', T[11]='$'\n\nBWT = \"av$dizzyyeca\"\n\nPHASE 4: C ARRAY\n\nCharacter frequencies in T: $ x1, a x2, c x1, d x1, e x1, i x1, v x1, y x2, z x2\n\nC['$'] = 0\nC['a'] = 1\nC['c'] = 3\nC['d'] = 4\nC['e'] = 5\nC['i'] = 6\nC['v'] = 7\nC['y'] = 8\nC['z'] = 10\n\nOcc COMPUTATIONS (Occ(c, k) = count of c in BWT[0..k-1]):\n\nBWT = \"av$dizzyyeca\"\n positions: 0='a', 1='v', 2='$', 3='d', 4='i', 5='z', 6='z', 7='y', 8='y', 9='e', 10='c', 11='a'\n\nOcc('z', 5) = count of 'z' in BWT[0..4] = \"av$di\" = 0\nOcc('z', 7) = count of 'z' in BWT[0..6] = \"av$dizz\" = 2\nOcc('y', 8) = count of 'y' in BWT[0..7] = \"av$dizzy\" = 1\nOcc('y', 10) = count of 'y' in BWT[0..9] = \"av$dizzyye\" = 2\n\nPHASE 5: LF-MAPPING\n\nLF(i) = C[BWT[i]] + Occ(BWT[i], i)\n\nLF(3): BWT[3]='d', C['d']=4, Occ('d',3)=0 (BWT[0..2]=\"av$\" has no 'd') -> LF(3) = 4\nLF(5): BWT[5]='z', C['z']=10, Occ('z',5)=0 -> LF(5) = 10\nLF(8): BWT[8]='y', C['y']=8, Occ('y',8)=1 -> LF(8) = 9\nLF(11): BWT[11]='a', C['a']=1, Occ('a',11)=1 (BWT[0..10]=\"av$dizzyyec\" has one 'a') -> LF(11) = 2\n\nPHASE 6: BACKWARD SEARCH FOR \"ze\"\n\nPattern \"ze\", processed right-to-left: first 'e', then 'z'.\n\nStep 1 - Initialize with 'e':\n lo = C['e'] = 5\n hi = C['i'] - 1 = 6 - 1 = 5 (next character after 'e' in alphabet present is 'i')\n Range: [5, 5]\n\nStep 2 - Extend with 'z':\n Occ('z', 5) = 0 (BWT[0..4] = \"av$di\")\n Occ('z', 6) = 1 (BWT[0..5] = \"av$diz\")\n new_lo = C['z'] + Occ('z', 5) = 10 + 0 = 10\n new_hi = C['z'] + Occ('z', 6) - 1 = 10 + 1 - 1 = 10\n Range: [10, 10]\n\nResult: 1 occurrence. SA[10] = 5. T[5..] = \"zeyyva$\". Confirmed.\n\nPHASE 7: LCP ARRAY AND DISTINCT SUBSTRINGS\n\nLCP[i] = length of longest common prefix between suffix at SA[i-1] and SA[i].\n\nLCP[0] = 0 (by definition)\nLCP[1] = 0: \"$\" vs \"a$\" -> no common prefix\nLCP[2] = 1: \"a$\" vs \"azidczeyyva$\" -> common prefix \"a\"\nLCP[3] = 0: \"azidczeyyva$\" vs \"czeyyva$\" -> no common prefix\nLCP[4] = 0: \"czeyyva$\" vs \"dczeyyva$\" -> no common prefix\nLCP[5] = 0: \"dczeyyva$\" vs \"eyyva$\" -> no common prefix\nLCP[6] = 0: \"eyyva$\" vs \"idczeyyva$\" -> no common prefix\nLCP[7] = 0: \"idczeyyva$\" vs \"va$\" -> no common prefix\nLCP[8] = 0: \"va$\" vs \"yva$\" -> no common prefix\nLCP[9] = 1: \"yva$\" vs \"yyva$\" -> common prefix \"y\"\nLCP[10] = 0: \"yyva$\" vs \"zeyyva$\" -> no common prefix\nLCP[11] = 1: \"zeyyva$\" vs \"zidczeyyva$\" -> common prefix \"z\"\n\nLCP = [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1]\n\nContributing pairs (non-zero LCP):\n- LCP[2] = 1: \"a$\" (pos 10) and \"azidczeyyva$\" (pos 0)\n- LCP[9] = 1: \"yva$\" (pos 8) and \"yyva$\" (pos 7)\n- LCP[11] = 1: \"zeyyva$\" (pos 5) and \"zidczeyyva$\" (pos 1)\n\nLCP sum = 1 + 1 + 1 = 3\n\nNon-empty distinct substrings = n(n+1)/2 - sum(LCP) = 12*13/2 - 3 = 78 - 3 = 75\n\nFINAL ANSWERS:\n1. T = \"azidczeyyva$\"\n2. Characters from S absent in T': 'b' and 'r'\n3. SA = [11, 10, 0, 4, 3, 6, 2, 9, 8, 7, 5, 1]; BWT = \"av$dizzyyeca\"\n4. Occ('z',5) = 0, Occ('z',7) = 2, Occ('y',8) = 1, Occ('y',10) = 2\n5. LF(3) = 4, LF(5) = 10, LF(8) = 9, LF(11) = 2\n6. Backward search \"ze\": [5,5] -> [10,10], using Occ('z',5) = 0 and Occ('z',6) = 1\n7. LCP sum = 3; contributing pairs at indices 2, 9, 11; non-empty distinct substrings = 75"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given `k` simple undirected graphs `G1..Gk` on the *same* labeled vertex set `V = {1,2,...,n}`.\n\nWe say a graph `Q` is a **blow-up pattern** (called a *fun graph*) of a graph `H` if there exists a partition of `V(H)` into `|V(Q)|` nonempty parts, one part per vertex of `Q`, such that:\n\n1. Each part induces either a **clique** or an **independent set** in `H`.\n2. For two distinct vertices `x,y` of `Q` with corresponding parts `Px, Py`:\n - if `xy` is an edge of `Q`, then **every** vertex of `Px` is adjacent in `H` to **every** vertex of `Py`;\n - if `xy` is not an edge of `Q`, then **no** vertex of `Px` is adjacent in `H` to **any** vertex of `Py`.\n\nA fun graph `Q` of `H` is called **super-minimal** (called *superb*) if among all fun graphs of `H`, it has the **fewest vertices**.\n\n---\n\n### The question\n\nFor each test case, decide whether there exist graphs `H1..Hk` that all share a common (unknown) vertex set `W`, such that:\n\n- For every `i`, the given graph `Gi` is a **superb fun graph** of `Hi`.\n\nAdditionally, the following cross-graph restriction must hold for each label `v ∈ V`:\n\n- If in some pair `(Gi,Hi)` the vertex `v` corresponds to an **independent-set part of size at least 2**, then there is **no** other pair `(Gj,Hj)` in which the same label `v` corresponds to a **clique part of size at least 2**.\n\nPrint `\"Yes\"` if such graphs `H1..Hk` exist, otherwise print `\"No\"`.\n\n---\n\n## Input\n- The first line: integer `t` — number of test cases.\nFor each test case:\n- One line: integers `n, k` (`1 ≤ n ≤ 300`, `1 ≤ k ≤ 10`)\n- Then for each `i=1..k`:\n - One line: integer `m` — number of edges in `Gi`\n - Next `m` lines: edges `u v` (`1 ≤ u < v ≤ n`)\n\nConstraints:\n- Sum of `m` over all graphs over all test cases ≤ `2 * 10^5`\n- Sum of `n` over all test cases ≤ `300`\n\n## Output\nFor each test case output `Yes` or `No` (case-insensitive).", "rubrics": [{"criterion": "Does the solution define a Type-A twin pair as a nonedge pair (a,b) with identical open neighborhoods?", "weight": 10}, {"criterion": "Does the solution define a Type-B twin pair as an edge pair (a,b) with identical closed neighborhoods?", "weight": 10}, {"criterion": "Does the solution add the clause (x_a ∨ x_b) for each Type-A pair (a,b)?", "weight": 10}, {"criterion": "Does the solution add the clause (¬x_a ∨ ¬x_b) for each Type-B pair (a,b)?", "weight": 10}, {"criterion": "Does the solution state that satisfiability is decided using SCC computation on the implication graph?", "weight": 20}, {"criterion": "Does the solution state that unsatisfiable occurs when x_v shares an SCC with ¬x_v for some v?", "weight": 20}, {"criterion": "Does the solution describe detecting Type-A pairs using equality of adjacency bitsets?", "weight": 10}, {"criterion": "Does the solution describe detecting Type-B pairs using equality of closed-neighborhood bitsets?", "weight": 10}], "golden_answer": "## Expert Solution (DSA — Graphs / 2-SAT)\n\n### Key structural notion: twins inside `Gi`\n\nFix one graph `Gi` on vertex set `{1..n}`.\n\n- **Type-A twin pair (open twins):** vertices `a ≠ b` such that \n `ab ∉ E(Gi)` and `N(a) = N(b)` (open neighborhoods identical).\n\n- **Type-B twin pair (closed twins):** vertices `a ≠ b` such that \n `ab ∈ E(Gi)` and `N[a] = N[b]` (closed neighborhoods identical).\n\nThese are exactly the pairs that can be merged in a fun-graph representation unless internal structure blocks the merge.\n\n### Why “size ≥ 2” matters for superbness\n\nAssume `Gi` is a superb fun graph of some `Hi` via parts `{P1..Pn}` (part `Pv` corresponds to label `v`).\n\n- If `a,b` are **Type-A** in `Gi` and both `Pa` and `Pb` are **independent sets**, then `Pa ∪ Pb` is also independent, and it has the same external adjacency pattern (because `a` and `b` have identical neighborhoods in `Gi`). \n This produces a valid fun graph with fewer vertices than `Gi`, contradicting superbness.\n\n Therefore, for every Type-A pair `(a,b)` in `Gi`, at least one of `{Pa,Pb}` must be a **clique with size ≥ 2** (a singleton clique does not prevent `Pa ∪ Pb` from being independent).\n\n- If `a,b` are **Type-B** in `Gi` and both `Pa` and `Pb` are **cliques**, then `Pa ∪ Pb` is a clique (edges inside parts are complete, and edges across parts are complete because `ab` is an edge of `Gi`). \n This again yields a smaller fun graph, contradicting superbness.\n\n Therefore, for every Type-B pair `(a,b)` in `Gi`, at least one of `{Pa,Pb}` must be an **independent set with size ≥ 2**.\n\n### Collapsing the multi-graph constraint into one boolean per label\n\nThe extra global rule says a label `v` cannot be realized as:\n- an **independent set of size ≥ 2** in some `Hi`\n- and a **clique of size ≥ 2** in another `Hj`.\n\nIntroduce one boolean variable per label:\n- `x_v = 1` means label `v` is allowed to be the “expanded clique label” (clique of size ≥ 2 whenever expansion is needed).\n- `x_v = 0` means label `v` is allowed to be the “expanded independent label” (independent set of size ≥ 2 whenever expansion is needed).\n\nLabels that end up size `1` in every `Hi` impose no restriction; they can be assigned either value.\n\nNow translate each twin constraint into a 2-CNF clause on `{x_v}`:\n\n- For every **Type-A** pair `(a,b)` in every `Gi`: \n at least one must be an expanded clique label \n ⇒ clause **`(x_a ∨ x_b)`**\n\n- For every **Type-B** pair `(a,b)` in every `Gi`: \n at least one must be an expanded independent label \n ⇒ clause **`(¬x_a ∨ ¬x_b)`**\n\nAll constraints across all `k` graphs become a single **2-SAT instance with `n` variables**.\n\n### Decision procedure (2-SAT)\n\nBuild the implication graph on `2n` literals.\n\n- Clause `(p ∨ q)` adds implications `¬p → q` and `¬q → p`.\n\nSo:\n- From `(x_a ∨ x_b)` add `¬x_a → x_b` and `¬x_b → x_a`.\n- From `(¬x_a ∨ ¬x_b)` add `x_a → ¬x_b` and `x_b → ¬x_a`.\n\nRun SCC (Kosaraju or Tarjan). The formula is satisfiable iff for every `v`,\n`x_v` and `¬x_v` are in different SCCs.\n\nIf satisfiable print `Yes`, else print `No`.\n\n### How to compute Type-A / Type-B pairs efficiently\n\nFor each `Gi`, store adjacency as bitsets `adj[v]` of length `n`.\n\nFor a pair `(a,b)`:\n- `ab ∉ E(Gi)` and `adj[a] == adj[b]` ⇒ Type-A\n- `ab ∈ E(Gi)` and `(adj[a] ∪ {a}) == (adj[b] ∪ {b})` ⇒ Type-B\n\nThis is `O(k * n^2 * (n/word_size))`, which is fine for `n ≤ 300`.\n\n### Complexity\n\nPer test case:\n- Building bitsets: `O(k * (n^2/word + m))`\n- Checking all pairs: `O(k * n^2 * (n/word))`\n- 2-SAT SCC: `O(n + number_of_clauses)`\n\nFits easily under the constraints.\n\n### Output\nFor each test case output `Yes` iff the constructed 2-SAT instance is satisfiable.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given an undirected connected graph G with n vertices and exactly n edges. The graph has no self-loops and no multiple edges. All edges have unit weight. Each edge has a state: **on** or **off**. Initially all edges are **off**.\n\nYou are given m queries (v, u). For each query, you must **toggle** (change on to off, or off to on) the state of **all edges on the shortest path** from v to u in G (using minimum number of edges).\n\nIf there are multiple shortest paths, you must choose the **lexicographically minimal** one, where a path is represented as the vertex sequence v, v1, v2, ..., u and sequences are compared element-by-element from left to right.\n\nAfter each query, output the number of connected components in the graph that contains all n vertices and **only the edges that are currently on**.\n\n### Input\n- First line: n m (3 <= n <= 10, 1 <= m <= 10)\n- Next n lines: each line contains two integers a b (1 <= a, b <= n, a != b) describing an edge\n- Next m lines: each line contains two integers v u (1 <= v, u <= n, v != u) describing a query\n\n### Output\nPrint m lines. The i-th line is the number of connected components after the i-th query.", "rubrics": [{"criterion": "For the input \"6 3\\n1 2\\n2 3\\n3 4\\n4 1\\n2 5\\n4 6\\n2 4\\n5 6\\n3 1\\n\", does the answer output exactly \"4\\n4\\n2\"?", "weight": 15}, {"criterion": "For the input \"5 4\\n1 2\\n2 3\\n3 1\\n3 4\\n4 5\\n1 2\\n2 3\\n1 3\\n5 1\\n\", does the answer output exactly \"4\\n3\\n3\\n1\"?", "weight": 20}, {"criterion": "For the input \"4 2\\n1 2\\n2 3\\n3 4\\n4 1\\n1 3\\n2 4\\n\", does the answer output exactly \"2\\n2\"?", "weight": 15}, {"criterion": "For the input \"5 2\\n1 2\\n2 3\\n3 1\\n1 4\\n4 5\\n5 2\\n5 3\\n\", does the answer output exactly \"2\\n3\"?", "weight": 15}, {"criterion": "For the input \"3 3\\n1 2\\n2 3\\n3 1\\n1 2\\n2 3\\n1 3\\n\", does the answer output exactly \"2\\n1\\n1\"?", "weight": 10}, {"criterion": "Does the answer demonstrate that when two cycle arcs have equal length, the lexicographically smaller path is chosen by comparing the next vertex after the start?", "weight": 5}, {"criterion": "Does the answer demonstrate state that a connected graph with n vertices and exactly n edges contains exactly one simple cycle?", "weight": 5}], "golden_answer": "## 1) Graph structure\nA connected graph with n vertices and n edges contains exactly one simple cycle. All other edges are bridges forming trees attached to cycle vertices.\n\nLet:\n- C = set of cycle vertices, k = |C|\n- onTreeEdges = number of ON edges not on the cycle\n- onCycleEdges = number of ON edges on the cycle\n\n## 2) Connected components formula\nTree edges alone give a forest:\n compsTrees = n - onTreeEdges\n\nFor the cycle on k vertices:\n- If onCycleEdges = k (all cycle edges ON): compsCycle = 1\n- If onCycleEdges < k: compsCycle = k - onCycleEdges\n\nThe k cycle vertices are k distinct components in the tree forest, merged by cycle edges:\n answer = compsTrees + compsCycle - k\n = (n - onTreeEdges) + compsCycle - k\n\n## 3) Path structure\nLet c(x) = the cycle vertex reached from x by following tree ancestors (or x itself if on cycle). Any shortest path v -> u consists of:\n1. Unique tree path v -> c(v)\n2. An arc on the cycle from c(v) to c(u)\n3. Unique tree path c(u) -> u\n\nOnly the cycle arc direction is ambiguous. Choose the shorter arc. If both arcs have equal length, choose the direction whose next vertex after c(v) on the cycle has the smaller vertex id, which makes the full vertex sequence lexicographically minimal.\n\n## 4) Implementation\nUse HLD + segment trees with range flip/sum on tree edges, and a separate segment tree on the k cycle edges. Each query: flip tree paths via HLD, flip cycle arc, then compute answer using the formula above.\n\nComplexity: O((n + m) log n) time, O(n) memory.\n\n## 5) Verification\n\n**Test A**\nInput:\n6 3\n1 2\n2 3\n3 4\n4 1\n2 5\n4 6\n2 4\n5 6\n3 1\n\nCycle: 1-2-3-4-1 (k=4). Tree edges: 2-5, 4-6.\n\nQuery (2,4): cycle arcs both length 2. Next vertices: 3 vs 1. Choose 1 (path 2-1-4). Toggle 2-1, 1-4. onTree=0, onCycle=2. answer = 6-0+4-2-4 = 4.\nQuery (5,6): tree 5-2, tree 6-4, cycle 2-1-4 (same tie-break). Toggle tree 5-2, 4-6 ON; cycle 2-1, 1-4 OFF. onTree=2, onCycle=0. answer = 6-2+4-0-4 = 4.\nQuery (3,1): cycle arcs length 2. Next vertices: 2 vs 4. Choose 2 (path 3-2-1). Toggle 3-2, 2-1. onTree=2, onCycle=2. answer = 6-2+4-2-4 = 2.\n\nOutput:\n4\n4\n2\n\n**Test B**\nInput:\n5 4\n1 2\n2 3\n3 1\n3 4\n4 5\n1 2\n2 3\n1 3\n5 1\n\nCycle: 1-2-3-1 (k=3). Tree edges: 3-4, 4-5.\n\nQuery (1,2): path 1-2 (length 1). Toggle 1-2. onTree=0, onCycle=1. answer = 5+3-1-3 = 4.\nQuery (2,3): path 2-3 (length 1). Toggle 2-3. onTree=0, onCycle=2. answer = 5+3-2-3 = 3.\nQuery (1,3): path 1-3 (length 1). Toggle 1-3. onTree=0, onCycle=3. answer = 5+1-3 = 3.\nQuery (5,1): tree 5-4-3, cycle 3-1 (length 1). Toggle tree 4-5, 3-4; cycle 3-1 OFF. onTree=2, onCycle=2. answer = 5-2+3-2-3 = 1.\n\nOutput:\n4\n3\n3\n1\n\n**Test C**\nInput:\n4 2\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n\nPure 4-cycle (k=4).\n\nQuery (1,3): arcs both length 2. Next vertex: 2 vs 4. Choose 2 (path 1-2-3). Toggle 1-2, 2-3. onCycle=2. answer = 4+4-2-4 = 2.\nQuery (2,4): arcs both length 2. Next vertex: 3 vs 1. Choose 1 (path 2-1-4). Toggle 2-1 (ON->OFF), 1-4 (OFF->ON). ON: {2-3, 1-4}. onCycle=2. answer = 4+4-2-4 = 2.\n\nOutput:\n2\n2\n\n**Test D**\nInput:\n5 2\n1 2\n2 3\n3 1\n1 4\n4 5\n5 2\n5 3\n\nCycle: 1-2-3 (k=3). Tree: 1-4, 4-5.\n\nQuery (5,2): tree 5-4-1, cycle 1-2 (length 1). Toggle tree 4-5, 1-4; cycle 1-2. onTree=2, onCycle=1. answer = 5-2+3-1-3 = 2.\nQuery (5,3): tree 5-4-1 (toggle back OFF), cycle 1-3 (length 1). Toggle 1-3. onTree=0, onCycle=2. answer = 5-0+3-2-3 = 3.\n\nOutput:\n2\n3\n\n**Test E**\nInput:\n3 3\n1 2\n2 3\n3 1\n1 2\n2 3\n1 3\n\nPure triangle (k=3).\n\nQuery (1,2): toggle 1-2. onCycle=1. answer = 3+3-1-3 = 2.\nQuery (2,3): toggle 2-3. onCycle=2. answer = 3+3-2-3 = 1.\nQuery (1,3): path 1-3 (length 1). Toggle 3-1. onCycle=3. answer = 3+1-3 = 1.\n\nOutput:\n2\n1\n1"}
{"domain": "Machine Learning & Artificial Intelligence", "prompt": "A Deep Belief Network processes 784-dimensional inputs to 10 output classes. The architecture connects Input → L1 → L2 → L3 → Output, where each connection has a weight matrix.\\n\\n**Configurations:**\\n\\n| Config | L1 | L2 | L3 | η | k | epochs |\\n|--------|-----|-----|-----|------|---|--------|\\n| A | 500 | 500 | 500 | 0.10 | 1 | 15 |\\n| B | 600 | 400 | 200 | 0.08 | 2 | 18 |\\n| C | 400 | 400 | 400 | 0.05 | 3 | 20 |\\n| D | 580 | 480 | 380 | 0.07 | 1 | 14 |\\n| E | 550 | 450 | 350 | 0.06 | 1 | 22 |\\n| F | 480 | 380 | 280 | 0.09 | 2 | 19 |\\n| G | 520 | 420 | 320 | 0.07 | 1 | 19 |\\n| H | 590 | 490 | 390 | 0.08 | 1 | 12 |\\n| J | 540 | 440 | 340 | 0.06 | 1 | 17 |\\n| K | 510 | 410 | 310 | 0.07 | 1 | 15 |\\n\\n**Observations (Ψ recorded before constraint validation):**\\n\\n| Config | M | T | Ψ |\\n|--------|------|------|------|\\n| A | 1794 | 22.5 | 68.4 |\\n| B | 1585 | 21.6 | 69.0 |\\n| D | 1839 | 20.2 | 69.9 |\\n| G | 1527 | 23.9 | 67.5 |\\n\\n**Constraints:**\\n\\n| | |\\n|---|---|\\n| c1 | M ≤ 2000 |\\n| c2 | T ≤ 28 |\\n| c3 | η ≥ 0.10 → epochs ≤ 15 |\\n| c4 | k ≥ 2 → T multiplied by (1 + 0.4×(k-1)) for c2 evaluation |\\n| c5 | L1 ≥ 600 → M multiplied by 1.08 for c1 evaluation |\\n| c6 | epochs > 20 → c2 threshold becomes 25 |\\n| c7 | Ψ > 70 → M ≤ 1750 |\\n\\nDetermine the valid configuration that maximizes Ψ.", "rubrics": [{"criterion": "The response states that Config K is the optimal valid configuration.", "weight": 10}, {"criterion": "The response states that Config K has Ψ equal to 71.0 or a value between 70.9 and 71.1.", "weight": 10}, {"criterion": "The response derives that M equals 0.002 multiplied by the total parameters.", "weight": 10}, {"criterion": "The response derives that T equals epochs multiplied by the sum of layer sizes divided by 1000.", "weight": 10}, {"criterion": "The response derives that Ψ is a linear function of T with slope between -0.60 and -0.70.", "weight": 15}, {"criterion": "The response states that Config H is invalid because it violates constraint c7.", "weight": 15}, {"criterion": "The response calculates that Config H has M equal to 1893 or a value between 1890 and 1900.", "weight": 10}, {"criterion": "The response identifies exactly five invalid configurations: B, C, E, F, and H.", "weight": 10}, {"criterion": "The response applies the c4 time adjustment factor of 1.4 when k equals 2.", "weight": 10}], "golden_answer": "Solution: DBN Configuration Optimization\n\nStep 1: Derive the Memory formula\n\nCalculate total parameters P for each calibration config:\n- Config A: P = 784×500 + 500×500 + 500×500 + 500×10 = 897,000\n- Config B: P = 784×600 + 600×400 + 400×200 + 200×10 = 792,400\n- Config D: P = 784×580 + 580×480 + 480×380 + 380×10 = 919,320\n- Config G: P = 784×520 + 520×420 + 420×320 + 320×10 = 763,680\n\nCheck the ratio M/P for each:\n- A: 1794 / 897000 = 0.002\n- B: 1585 / 792400 = 0.002\n- D: 1839 / 919320 = 0.002\n- G: 1527 / 763680 = 0.002\n\nMemory formula: M = 0.002 × P\n\n\nStep 2: Derive the Time formula\n\nCheck the pattern with epochs and layer sums:\n- A: 15 × (500+500+500) / 1000 = 15 × 1500 / 1000 = 22.5 matches\n- B: 18 × (600+400+200) / 1000 = 18 × 1200 / 1000 = 21.6 matches\n- D: 14 × (580+480+380) / 1000 = 14 × 1440 / 1000 = 20.16 matches\n- G: 19 × (520+420+320) / 1000 = 19 × 1260 / 1000 = 23.94 matches\n\nTime formula: T = epochs × (L1 + L2 + L3) / 1000\n\nNote: Config B has k=2 but its T=21.6 is the base time, not adjusted. This means T in observations is base time before c4 adjustment.\n\n\nStep 3: Derive the Ψ formula\n\nPlot T vs Ψ from calibration data:\n- A: T=22.5, Ψ=68.4\n- B: T=21.6, Ψ=69.0\n- D: T=20.2, Ψ=69.9\n- G: T=23.9, Ψ=67.5\n\nCalculate slope using A and D:\nslope = (68.4 - 69.9) / (22.5 - 20.2) = -1.5 / 2.3 = -0.652\n\nCalculate intercept:\nintercept = 68.4 + 0.652 × 22.5 = 83.07\n\nVerify with all points:\n- A: 83.07 - 0.652×22.5 = 68.4 correct\n- B: 83.07 - 0.652×21.6 = 69.0 correct\n- D: 83.07 - 0.652×20.2 = 69.9 correct\n- G: 83.07 - 0.652×23.9 = 67.5 correct\n\nΨ formula: Ψ = 83.07 - 0.652 × T\n\n\nStep 4: Calculate values for all configurations\n\nConfig A: P=897000, M=1794, T=22.5, Ψ=68.4\nConfig B: P=792400, M=1585, T_base=21.6, T_adj=30.2, Ψ=69.0\nConfig C: P=637600, M=1275, T_base=24.0, T_adj=43.2, Ψ=67.4\nConfig D: P=919320, M=1839, T=20.2, Ψ=69.9\nConfig E: P=839700, M=1679, T=29.7, Ψ=63.7\nConfig F: P=667920, M=1336, T_base=21.7, T_adj=30.3, Ψ=68.9\nConfig G: P=763680, M=1527, T=23.9, Ψ=67.5\nConfig H: P=946660, M=1893, T=17.6, Ψ=71.6\nConfig J: P=813960, M=1628, T=22.4, Ψ=68.4\nConfig K: P=739140, M=1478, T=18.5, Ψ=71.0\n\n\nStep 5: Check constraints for each configuration\n\nConfig A:\n- c1: M=1794 ≤ 2000, pass\n- c2: T=22.5 ≤ 28, pass\n- c3: η=0.10, epochs=15 ≤ 15, pass\n- c7: Ψ=68.4 ≤ 70, does not trigger\n- Result: VALID\n\nConfig B:\n- c5: L1=600, M_eff = 1585 × 1.08 = 1712 ≤ 2000, pass\n- c4: k=2, T_adj = 21.6 × 1.4 = 30.2\n- c2: T_adj=30.2 > 28, FAIL\n- Result: INVALID\n\nConfig C:\n- c4: k=3, T_adj = 24 × 1.8 = 43.2\n- c2: T_adj=43.2 > 28, FAIL\n- Result: INVALID\n\nConfig D:\n- c1: M=1839 ≤ 2000, pass\n- c2: T=20.2 ≤ 28, pass\n- c7: Ψ=69.9 ≤ 70, does not trigger\n- Result: VALID\n\nConfig E:\n- c6: epochs=22 > 20, threshold becomes 25\n- c2: T=29.7 > 25, FAIL\n- Result: INVALID\n\nConfig F:\n- c4: k=2, T_adj = 21.7 × 1.4 = 30.3\n- c2: T_adj=30.3 > 28, FAIL\n- Result: INVALID\n\nConfig G:\n- c1: M=1527 ≤ 2000, pass\n- c2: T=23.9 ≤ 28, pass\n- c7: Ψ=67.5 ≤ 70, does not trigger\n- Result: VALID\n\nConfig H:\n- c1: M=1893 ≤ 2000, pass\n- c2: T=17.6 ≤ 28, pass\n- c7: Ψ=71.6 > 70, triggers constraint\n- c7 requires: M ≤ 1750\n- M=1893 > 1750, FAIL\n- Result: INVALID\n\nConfig J:\n- c1: M=1628 ≤ 2000, pass\n- c2: T=22.4 ≤ 28, pass\n- c7: Ψ=68.4 ≤ 70, does not trigger\n- Result: VALID\n\nConfig K:\n- c1: M=1478 ≤ 2000, pass\n- c2: T=18.5 ≤ 28, pass\n- c7: Ψ=71.0 > 70, triggers constraint\n- c7 requires: M ≤ 1750\n- M=1478 ≤ 1750, pass\n- Result: VALID\n\n\nStep 6: Rank valid configurations\n\nValid configs by Ψ:\n1. K: Ψ = 71.0\n2. D: Ψ = 69.9\n3. A: Ψ = 68.4\n4. J: Ψ = 68.4\n5. G: Ψ = 67.5\n\nInvalid configs:\n- B: fails c2 (T_adj = 30.2 > 28)\n- C: fails c2 (T_adj = 43.2 > 28)\n- E: fails c2 with c6 (T = 29.7 > 25)\n- F: fails c2 (T_adj = 30.3 > 28)\n- H: fails c7 (Ψ > 70 but M = 1893 > 1750)\n\n\nAnswer\n\nThe valid configuration that maximizes Ψ is Config K.\n\nConfig K values:\n- L1 = 510, L2 = 410, L3 = 310\n- η = 0.07, k = 1, epochs = 15\n- M = 1478\n- T = 18.45\n- Ψ = 71.0\n\nConfig H appears to have higher Ψ (71.6) but is invalid because c7 requires M ≤ 1750 when Ψ > 70, and H has M = 1893.\n"}
{"domain": "Computer Systems & Operating Systems", "prompt": "System overview\nA single-core kernel manages five user processes P1 through P5 over discrete ticks.\nAt every tick, three subsystems interact: an MLFQ scheduler with three queues and dynamic Q0 quantum, demand-paged virtual memory with TLB and Enhanced Second Chance replacement, and a disk using C-LOOK with anti-starvation.\nPhysical memory has frames F1..F12. Disk has 64 sectors and arm starts at sector 0.\nPage p of process Pk is stored at sector (k*13 + p*3 + 1) mod 64.\n\nInitial conditions\nAt tick 0, P1, P2, and P4 are READY in Q0. P3 does not exist. P5 is NOT READY until tick 3.\nInitial Q0 order is PID order among READY processes. No process starts blocked.\nPinned page-table frames are fixed and never evictable: F1=PT:P1, F2=PT:P2, F3=PT:P4.\nWhen P5 becomes READY at tick 3 it receives F5=PT:P5. When P3 is created at tick 10 it receives F4=PT:P3.\nData frames are therefore exactly F6..F12 for the full run.\n\nProcess programs\nP1: R(0), W(1), R(2), R(3), W(4), R(1), R(5), W(6), R(0), W(7), R(8), DONE.\nP2: R(0), R(14), W(15), R(1), R(2), W(14), R(3), W(4), R(14), DONE.\nP3: W(0), R(1), W(2), R(3), R(4), W(5), R(6), DONE.\nP4: R(0), R(14), W(14), R(1), R(15), W(2), R(3), W(15), DONE.\nP5: R(0), R(1), R(2), W(3), W(4), R(5), R(0), W(6), DONE.\n\nFork and shared mapping\nAt the start of tick 10, before scheduling, P3 is created from P1.\nFork blocks P1 for exactly tick 10.\nDuring tick 10, P3 exists and is active for accounting, but P3 is not READY and is not schedulable.\nAt tick 11, both P1 and P3 are READY in Q0.\nP3 inherits P1 mappings as read-only shared mappings. A write by P1 or P3 to an inherited shared page triggers COW.\nP2 and P4 share VPN 14 and 15 in one shared frame pair.\nThe first of P2 or P4 to access VPN 14 establishes the shared mapping and allocates one physical frame for VPN 14 (loaded via the normal page-in path). VPN 15 is demand-paged independently into its own shared frame on first access. Whichever process did not trigger the original allocation attaches to the existing shared frame on its first access to VPN 14 or VPN 15; if that frame is still being loaded, the attaching process page-faults and waits for the same page-in to complete.\nWhen one writes shared VPN 14 or 15, the other process's TLB entries for those VPNs are invalidated exactly at the next context-switch boundary away from the writer.\n\nPer-tick execution order\nAt the start of each tick, execute the following order exactly.\n1) Apply reference-bit decay on ticks 12, 24, 36, 48, 60.\n2) Apply global boost on ticks 25 and 50.\n3) Apply Q2 aging promotions.\n4) Apply arrivals/unblocks that become READY at this tick.\n5) If CPU is free, scheduler chooses next READY process.\n6) If chosen PID differs from previously running PID or previous state was IDLE, consume one context-switch tick; exception: the first dispatch from initial IDLE at tick 0 consumes 0 ticks and is not counted.\n7) Otherwise execute one unit of running work.\n8) Disk progresses one unit of current seek/transfer if active; if idle, it selects next request immediately and also consumes first seek unit in the same tick.\nScheduler tie-break in any queue is lowest PID.\n\nScheduling rules\nQ0 quantum is 2 + ((pf_non_cow + cow_faults_by_process) mod 3), sampled once at dispatch and fixed for that dispatch.\nQ1 quantum is 5. Q2 quantum is 9. Quantum never changes mid-dispatch.\nNew READY and newly unblocked processes always enter Q0.\nBlocking does not demote. On unblock, process enters Q0.\nQuantum expiry without blocking demotes one level; Q2 remains Q2 on expiry.\nScheduler re-evaluates only when running process blocks, exhausts quantum, or terminates.\nAging rule: waiting 7 consecutive ticks in Q2 without dispatch promotes to Q0 at the start of the next tick.\n\nContext-switch accounting\nCount and charge 1 tick for every transition between distinct running states, including process-to-process, process-to-idle, and idle-to-process.\nThe only exception is the unique initial IDLE-to-first-process dispatch at tick 0, which has zero cost and is not counted.\nEvery charged context-switch tick flushes entire TLB and applies pending shared-region invalidations.\n\nTLB rules\nTLB capacity is 4 and fully associative.\nHit: memory operation costs 1 tick, increments entry hit_count by 1, and sets last_access_tick to current tick.\nMiss with resident page: operation costs 2 ticks total (walk plus access), then insert/update entry with hit_count=0 and last_access_tick=current tick.\nOn insert when full, evict entry with minimum score (last_access_tick + 2*hit_count), tie by smallest VPN, then smallest PID.\nFlush removes all entries and counters.\nAny successful memory access (read or write, hit path or resident-miss path) sets the referenced frame's R bit immediately in that same tick before any replacement decision caused by that access.\n\nPaging and replacement rules\nAccess to non-resident page causes immediate page fault and block; page-in request is enqueued in that same tick.\nEnhanced Second Chance class order is fixed: C0=(R=0,D=0), C1=(R=0,D=1), C2=(R=1,D=0), C3=(R=1,D=1).\nVictim selection is global over eligible data frames F6..F12.\nWithin the lowest non-empty class, choose oldest load_tick, tie lowest frame number.\nThis ordering is complete and does not depend on sweep start position.\nSweep does not modify reference bits. Reference bits change only on access and global decay ticks.\nload_tick is defined as the tick at which the corresponding page-in transfer completes and the page becomes resident in its frame.\n\nMinimum residency rule\nTarget floor is 1 data frame per active process, treated as a soft floor.\nActive means process exists and is not terminated.\nDuring victim eligibility, first consider only candidates whose owner currently holds more than 1 data frame (prefer to shrink larger holders). If no such candidate exists, allow eviction from owners holding exactly 1 data frame.\nIf still none (only possible when all data frames are PENDING), wait until any pending write-back completes.\nThis fallback order is mandatory and deterministic.\n\nDirty eviction and COW timing\nIf chosen victim is dirty, schedule write-back and mark frame PENDING immediately.\nA PENDING frame cannot be reused until write-back completes.\nThe faulting page-in cannot claim that frame before completion.\nCOW fault blocks writer immediately, counts toward cow_faults and toward writer dynamic-quantum cumulative count, but not toward reported per-process page_faults.\nOnce destination frame is available, COW service consumes exactly 2 CPU ticks (copy then remap).\nThose 2 ticks are kernel-work ticks executed while that process is RUNNING; they do not execute a user memory operation and do not decrement that dispatch quantum counter.\nIf replacement/write-back is needed, those disk delays occur before the 2 COW CPU ticks.\nCOW faults always forfeit remaining quantum at fault time and re-enter through Q0 when unblocked.\nA write memory operation sets the frame D bit immediately in the tick of that write, regardless of whether translation came from a TLB hit or from a resident-page miss path.\nFor COW, the newly allocated destination frame starts clean after copy; the triggering write then sets D immediately when that write is applied.\n\nDisk rules\nSingle arm and one active request at a time.\nRequest type is READ (page-in) or WRITE (write-back).\nSame-tick enqueue order is deterministic by event order within tick; if event step ties, lower PID then lower VPN.\nPriority rule: any request with wait_time > 6 is starved and has absolute priority; among starved requests use enqueue_tick then lower sector.\nIf no starved request exists, use C-LOOK in increasing-sector direction only: choose smallest pending sector >= current arm; if none exists, wrap to global smallest pending sector.\nSeek time is ceil(abs(current-target)/2), minimum 1. Transfer time is 1.\nAt equal seek distance, READ beats WRITE; remaining ties use earlier enqueue_tick then lower sector.\n\nUnblock timing\nIf page-in transfer completes at tick T, the process becomes READY at start of tick T+1 and enters Q0 at that time.\nRequests generated during a context-switch tick are enqueued in that same tick and are eligible for disk selection in step 8 of that same tick.\n\nRequired output\nProduce the unique deterministic execution trace and print exactly one key=value line per item, in this exact order:\npage_faults=f1,f2,f3,f4,f5\ntlb_hits=total\ncontext_switches=count\ncow_faults=count\ndirty_writebacks=count\ntotal_seek_ticks=sum\ndisk_arm_final=sector\ncompletion_order=PID1,PID2,PID3,PID4,PID5\np3_first_cow_tick=tick\nlast_tick=tick\nfinal_frame_map=F1:owner,F2:owner,F3:owner,F4:owner,F5:owner,F6:owner,F7:owner,F8:owner,F9:owner,F10:owner,F11:owner,F12:owner\n\nOutput value conventions\nFor final_frame_map owner, use Pk:n for process-page, PT:Pk for page-table frame, PENDING-WRITE:Pk:n if write-back is still in progress at simulation end, or FREE.\nFor p3_first_cow_tick use NA if P3 never triggers COW.", "rubrics": [{"criterion": "Does the answer report cow_faults exactly as 1?", "weight": 5}, {"criterion": "Does the answer report tlb_hits exactly as 1?", "weight": 5}, {"criterion": "Does the answer report p3_first_cow_tick exactly as 16?", "weight": 10}, {"criterion": "Does the answer report context_switches exactly as 83?", "weight": 10}, {"criterion": "Does the answer report dirty_writebacks exactly as 11?", "weight": 10}, {"criterion": "Does the answer report disk_arm_final exactly as 39?", "weight": 10}, {"criterion": "Does the answer report page_faults exactly as 11,10,6,7,8?", "weight": 15}, {"criterion": "Does the answer report completion_order exactly as 3,4,1,5,2?", "weight": 10}, {"criterion": "Does the answer report total_seek_ticks exactly as 564?", "weight": 15}, {"criterion": "Does the answer report last_tick exactly as 623?", "weight": 15}, {"criterion": "Does the answer report final_frame_map exactly as F1:PT:P1,F2:PT:P2,F3:PT:P4,F4:PT:P3,F5:PT:P5,F6:P1:7,F7:P2:14,F8:P2:4,F9:P4:15,F10:P5:6,F11:P1:8,F12:P2:3?", "weight": 15}], "golden_answer": "# Golden Solution: Single-Core Kernel Simulation (MLFQ + Demand-Paged VM + C-LOOK Disk)\n\n## 1. Setup and Initialization\n\nPhysical memory holds 12 frames. Frames F1–F5 are pinned page tables:\n\n| Frame | Role |\n|-------|------|\n| F1 | PT:P1 |\n| F2 | PT:P2 |\n| F3 | PT:P4 |\n| F4 | PT:P3 (allocated at tick 10) |\n| F5 | PT:P5 (allocated at tick 3) |\n\nData frames available throughout the run: F6–F12 (7 frames total).\nDisk arm starts at sector 0. Sector formula: `(k*13 + p*3 + 1) mod 64`.\n\nAt tick 0: P1, P2, P4 are READY in Q0. P5 arrives at tick 3. P3 is forked from P1 at tick 10.\n\n---\n\n## 2. Detailed Tick-by-Tick Trace (Ticks 0–30)\n\n### Tick 0\n\n- Steps 1–4: Nothing applicable.\n- Step 5: CPU idle. Pick P1 (lowest PID among {P1, P2, P4}).\n- Step 6: First dispatch from initial IDLE — zero cost, not counted.\n Dispatch P1 with Q0 quantum = 2 + ((0+0) mod 3) = 2.\n- Step 7: P1 executes R(0). TLB empty. Page table empty. **Page fault** (P1 pf=1). P1 blocks. Allocate F6 for P1:page0. Enqueue page-in sector (1·13 + 0·3 + 1) mod 64 = 14.\n- Step 8: Disk idle. Select P1:page0 (only request). Seek from 0 to 14: ceil(14/2)=7. Begin, consume first seek unit (6 remaining).\n\n### Tick 1\n\n- Step 5: P1 blocked (prev_pid=P1). CPU free. Pick P2 (lowest PID among {P2, P4}).\n- Step 6: **CS #1** P1→P2. TLB flush. Dispatch P2 Q0 quantum=2.\n- Step 8: Disk seek (5 remaining).\n\n### Tick 2\n\n- Step 7: P2 executes R(0). Page fault (P2 pf=1). Allocate F7. Enqueue page-in sector 27.\n- Step 8: Disk seek (4 remaining).\n\n### Tick 3\n\n- Step 4: P5 arrives, READY Q0. F5 assigned as PT:P5.\n- Step 5: P2 blocked (prev_pid=P2). Pick P4 (pid 4 < pid 5).\n- Step 6: **CS #2** P2→P4. Dispatch P4 Q0 quantum=2.\n- Step 8: Disk seek (3 remaining).\n\n### Tick 4\n\n- Step 7: P4 executes R(0). Page fault (P4 pf=1). Allocate F8. Enqueue page-in sector 53.\n- Step 8: Disk seek (2 remaining).\n\n### Tick 5\n\n- Step 5: P4 blocked. Pick P5.\n- Step 6: **CS #3** P4→P5. Dispatch P5 Q0 quantum=2.\n- Step 8: Disk seek (1 remaining).\n\n### Tick 6\n\n- Step 7: P5 executes R(0). Page fault (P5 pf=1). Allocate F9. Enqueue page-in sector 2.\n- Step 8: Disk seek completes. Arm at 14. Transfer begins.\n\n### Tick 7\n\n- Step 5: P5 blocked. No READY processes.\n- Step 6: **CS #4** P5→IDLE. TLB flush.\n- Step 8: Disk transfer completes. P1:page0 loaded into F6 (load_tick=7). Unblock scheduled for tick 8.\n\n### Tick 8\n\n- Step 4: P1 unblocks → READY Q0.\n- Step 5: Pick P1.\n- Step 6: **CS #5** IDLE→P1. Dispatch P1 Q0 quantum = 2+((1+0) mod 3) = 3.\n- Step 8: Disk idle. Select P2:page0 (sector 27). Starvation check: wait 8−2=6, not >6. C-LOOK: 27 ≥ 14. Seek ceil(13/2)=7. Begin (6 remaining).\n\n### Tick 9\n\n- Step 7: P1 R(0). TLB empty (flushed). Page table: page0→F6. F6 resident. TLB miss (walk tick). Set R=1 on F6. Quantum 3→2.\n- Step 8: Disk seek (5 remaining).\n\n### Tick 10\n\n- Step 4: **Fork.** P3 created from P1. P1 blocked. P1's mid-TLB-miss state (op_rem) reset to 0. P3 inherits P1 page table: {page0→F6}. Both P1 and P3 mark page0 as COW. F4 allocated as PT:P3. P3 active from tick 10.\n- Step 5: P1 blocked. P3 exists and is active for resource accounting, but not yet READY (unblocks at tick 11). No schedulable process.\n- Step 6: **CS #6** P1→IDLE.\n- Step 8: Disk seek (4 remaining).\n\n### Tick 11\n\n- Step 4: Fork unblock. P1 and P3 both READY in Q0.\n- Step 5: Pick P1 (pid 1 < pid 3).\n- Step 6: **CS #7** IDLE→P1. Dispatch P1 Q0 quantum=3.\n- Step 8: Disk seek (3 remaining).\n\n### Tick 12\n\n- Step 1: **Ref-bit decay.** All R bits on F6–F12 cleared (F6.R becomes 0).\n- Step 7: P1 R(0). TLB empty (flushed at CS). Page table: page0→F6. Resident. TLB miss walk. R set to 1. Quantum 3→2.\n- Step 8: Disk seek (2 remaining).\n\n### Tick 13\n\n- Step 7: P1 R(0) TLB miss complete (access tick). R re-asserted, TLB insert for page0. PC advances to W(1). Quantum 2→1.\n- Step 8: Disk seek completes. Arm at 27. Transfer begins.\n\n### Tick 14\n\n- Step 7: P1 W(1). Page1 not in page table. **Page fault** (P1 pf=2). Allocate F10. Enqueue page-in sector 17.\n- Step 8: Disk transfer in progress for P2:page0.\n\n### Tick 15\n\n- Step 5: P1 blocked. Pick P3 (only READY Q0).\n- Step 6: **CS #8** P1→P3. Dispatch P3 Q0 quantum = 2+((0+0) mod 3) = 2.\n- Step 8: Disk transfer completes. P2:page0 → F7 (load_tick=15). Unblock at tick 16. Disk selects next: P4:page0 (sector 53, eq=4, wait=15−4=11>6, starved), P5:page0 (sector 2, eq=6, wait=9>6, starved), P1:page1 (sector 17, eq=14, wait=1, not starved). Starved requests: P4(eq=4), P5(eq=6). FCFS by enqueue_tick → P4(eq=4). Seek ceil((53−27)/2)=13. Begin (12 remaining).\n\n### Tick 16\n\n- Step 4: P2 unblocks → READY Q0.\n- Step 7: P3 executes W(0). Page0 is in cow_pages (inherited from P1). **COW fault** (cow_faults=1). p3_first_cow_tick = 16. Allocate F11 for P3:page0. Frame immediately available (F11 free). P3:page0→F11. load_tick=16. P3 → READY Q0 with cow_work_remaining=2.\n- Step 8: Disk seek (11 remaining).\n\n### Ticks 17–20\n\n- **Tick 17:** CS #9 P3→P2. Dispatch P2 Q0 quantum=3 (pf=1).\n- **Tick 18:** P2 R(0) TLB miss walk on F7. Quantum 3→2.\n- **Tick 19:** P2 R(0) miss complete. TLB insert. Quantum 2→1.\n- **Tick 20:** P2 R(14). VPN 14 not in page table. Not in mmap yet (first access). **Page fault** (P2 pf=2). Allocate F12. Enqueue page-in sector (2·13+14·3+1) mod 64 = 5. Establishes shared mmap: mmap[14]=F12.\n\n### Ticks 21–23\n\n- **Tick 21:** CS #10 P2→P3. Dispatch P3 Q0 quantum=3 (pf=0, cow=1). cow_work_remaining=2.\n- **Tick 22:** P3 COW kernel tick 1 (no quantum decrement). cow_work_remaining=1.\n- **Tick 23:** P3 COW kernel tick 2 complete. Write applied to F11: R=1, D=1. PC advances past W(0).\n\n### Tick 24\n\n- Step 1: **Ref-bit decay.** All R cleared.\n- Step 7: P3 R(1). Page1 not in page table. **Page fault** (P3 pf=1). Need frame: all data frames occupied or reserved. Non-reserved frames: F6(P1:page0, C0, load=7), F7(P2:page0, C0, load=15), F11(P3:page0, C1, load=16). Soft-floor: each active owner has 1 frame. No owner >1. Fallback to exactly 1. Lowest class C0: F6(load=7) vs F7(load=15). Oldest → **evict F6** (P1:page0, clean). Enqueue page-in for P3:page1, sector 43.\n\n### Tick 25\n\n- Step 2: **Global boost** (all READY→Q0).\n- Step 5: P3 blocked. No READY. CS #11 P3→IDLE.\n\n### Ticks 26–29: IDLE\n\nDisk servicing P4:page0 (sector 53, seek=13).\n\n### Tick 29\n\n- Step 8: Disk transfer completes. P4:page0 → F8 (load_tick=29). Unblock at tick 30.\n\n### Tick 30\n\n- Step 4: P4 unblocks → READY Q0.\n- CS #12 IDLE→P4. Dispatch P4 Q0 quantum = 2+((1+0) mod 3) = 3.\n- Step 8: Disk selects P5:page0 (sector 2, starved since eq=6, wait=24). Seek ceil((53−2)/2)=ceil(51/2)=26. Begin.\n\n---\n\n## 3. Mid-Simulation Highlights (Ticks 30–523)\n\nFrom this point the simulation enters a pattern of: process dispatches, attempts one or two memory operations (each requiring TLB miss = 2 ticks), page-faults, blocks, and waits for long disk seeks. The 7 data frames are under constant pressure from 5 active processes.\n\n**Shared mmap resolution (tick 33):** P4 attempts R(14). The shared frame F12 (VPN 14) is still reserved (P2's page-in in progress). P4 page-faults (P4 pf=2) and waits for the same page-in — no separate disk request. This is the mmap piggyback: 42 total page faults but only 41 disk READs.\n\n**Tick 73:** Both P2 and P4 unblock when F12's page-in completes at tick 72. P2 gets dispatched first (lower PID).\n\n**Tick 80:** P4 W(14) — TLB hit (the only TLB hit in the entire simulation). The TLB entry for VPN 14 was inserted at tick 79 after the resident-miss completed. The write sets F12.D=1 and schedules invalidation of P2's TLB entries for VPN 14/15 at next CS.\n\n**VPN 15 handling:** P2 first accesses VPN 15 at tick 76 (W(15) page fault). F9 allocated, page-in sector 8. P4 later accesses VPN 15 at tick 219, finding it mmap-resident in F9 and attaching without a new page-in.\n\n**Thrashing examples:** P2 suffers two double-faults. R(1) first faults at tick 132, page-in completes at tick 252, but F12 is evicted at tick 253 by P1's R(1) page fault — P2 must re-fault at tick 255. R(2) first faults at tick 396, loaded at tick 434, but evicted at tick 436 — re-fault at tick 438. P4's W(15) experiences similar thrashing: faults at tick 411, loaded at tick 436, evicted at tick 438, then re-faults at tick 440.\n\n**No process ever reaches Q2.** Every quantum expiry demotes Q0→Q1, but the process always page-faults before exhausting Q1's quantum of 5, which sends it back to Q0 on unblock. Aging never triggers.\n\n### Complete quantum expiry list\n\n| Tick | Process | Transition |\n|------|---------|------------|\n| 125 | P1 | Q0→Q1 |\n| 132 | P2 | Q0→Q1 |\n| 153 | P3 | Q0→Q1 |\n| 173 | P5 | Q0→Q1 |\n| 219 | P4 | Q0→Q1 |\n| 306 | P1 | Q0→Q1 |\n| 416 | P3 | Q0→Q1 |\n| 476 | P5 | Q0→Q1 |\n| 479 | P1 | Q0→Q1 |\n| 616 | P2 | Q0→Q1 |\n\nOf these 10 expiries, 9 result in re-dispatch of the same process (it is the only READY candidate). The exception is tick 476 where P5 expires and P1 (newly unblocked) is selected instead (CS #64 P5→P1).\n\n---\n\n## 4. Complete Disk I/O Schedule\n\n52 disk operations total: 41 READs (page-ins) + 11 WRITEs (dirty writebacks). One additional page fault (P4's mmap piggyback at tick 33) produces no disk request.\n\n| # | Begin | Done | Kind | Sector | Process:VPN | Frame | Seek | Arm After |\n|---|-------|------|------|--------|-------------|-------|------|-----------|\n| 1 | 0 | 7 | READ | 14 | P1:0 | F6 | 7 | 14 |\n| 2 | 8 | 15 | READ | 27 | P2:0 | F7 | 7 | 27 |\n| 3 | 16 | 29 | READ | 53 | P4:0 | F8 | 13 | 53 |\n| 4 | 30 | 56 | READ | 2 | P5:0 | F9 | 26 | 2 |\n| 5 | 57 | 65 | READ | 17 | P1:1 | F10 | 8 | 17 |\n| 6 | 66 | 72 | READ | 5 | P2:14 | F12 | 6 | 5 |\n| 7 | 73 | 92 | READ | 43 | P3:1 | F6 | 19 | 43 |\n| 8 | 93 | 112 | READ | 5 | P5:1 | F7 | 19 | 5 |\n| 9 | 113 | 121 | READ | 20 | P1:2 | F8 | 8 | 20 |\n| 10 | 122 | 128 | READ | 8 | P2:15 | F9 | 6 | 8 |\n| 11 | 129 | 145 | WRITE | 40 | P3:0 | F11 | 16 | 40 |\n| 12 | 146 | 149 | READ | 46 | P3:2 | F6 | 3 | 46 |\n| 13 | 150 | 169 | READ | 8 | P5:2 | F7 | 19 | 8 |\n| 14 | 170 | 178 | READ | 23 | P1:3 | F8 | 8 | 23 |\n| 15 | 179 | 188 | WRITE | 5 | P2:14 | F12 | 9 | 5 |\n| 16 | 189 | 215 | READ | 56 | P4:1 | F11 | 26 | 56 |\n| 17 | 216 | 236 | WRITE | 17 | P1:1 | F10 | 20 | 17 |\n| 18 | 237 | 240 | READ | 11 | P5:3 | F7 | 3 | 11 |\n| 19 | 241 | 249 | READ | 26 | P1:4 | F8 | 8 | 26 |\n| 20 | 250 | 252 | READ | 30 | P2:1 | F12 | 2 | 30 |\n| 21 | 253 | 268 | READ | 59 | P4:2 | F11 | 15 | 59 |\n| 22 | 269 | 274 | READ | 49 | P3:3 | F10 | 5 | 49 |\n| 23 | 275 | 296 | WRITE | 8 | P2:15 | F9 | 21 | 8 |\n| 24 | 297 | 302 | READ | 17 | P1:1 | F12 | 5 | 17 |\n| 25 | 303 | 318 | WRITE | 46 | P3:2 | F6 | 15 | 46 |\n| 26 | 319 | 337 | WRITE | 11 | P5:3 | F7 | 18 | 11 |\n| 27 | 338 | 359 | READ | 52 | P3:4 | F10 | 21 | 52 |\n| 28 | 360 | 379 | READ | 14 | P5:4 | F9 | 19 | 14 |\n| 29 | 380 | 388 | READ | 29 | P1:5 | F12 | 8 | 29 |\n| 30 | 389 | 390 | READ | 30 | P2:1 | F6 | 1 | 30 |\n| 31 | 391 | 407 | READ | 62 | P4:3 | F7 | 16 | 62 |\n| 32 | 408 | 412 | READ | 55 | P3:5 | F10 | 4 | 55 |\n| 33 | 413 | 428 | WRITE | 26 | P1:4 | F8 | 15 | 26 |\n| 34 | 429 | 432 | READ | 32 | P1:6 | F12 | 3 | 32 |\n| 35 | 433 | 434 | READ | 33 | P2:2 | F6 | 1 | 33 |\n| 36 | 435 | 436 | READ | 34 | P4:15 | F7 | 1 | 34 |\n| 37 | 437 | 450 | WRITE | 59 | P4:2 | F11 | 13 | 59 |\n| 38 | 451 | 472 | READ | 17 | P5:5 | F8 | 21 | 17 |\n| 39 | 473 | 475 | READ | 14 | P1:0 | F6 | 2 | 14 |\n| 40 | 476 | 486 | READ | 33 | P2:2 | F7 | 10 | 33 |\n| 41 | 487 | 497 | WRITE | 14 | P5:4 | F9 | 10 | 14 |\n| 42 | 498 | 520 | READ | 58 | P3:6 | F11 | 22 | 58 |\n| 43 | 521 | 533 | READ | 35 | P1:7 | F6 | 12 | 35 |\n| 44 | 534 | 551 | READ | 2 | P5:0 | F8 | 17 | 2 |\n| 45 | 552 | 554 | READ | 5 | P2:14 | F7 | 2 | 5 |\n| 46 | 555 | 570 | READ | 34 | P4:15 | F9 | 15 | 34 |\n| 47 | 571 | 573 | READ | 38 | P1:8 | F11 | 2 | 38 |\n| 48 | 574 | 583 | WRITE | 55 | P3:5 | F10 | 9 | 55 |\n| 49 | 584 | 596 | WRITE | 32 | P1:6 | F12 | 12 | 32 |\n| 50 | 597 | 603 | READ | 20 | P5:6 | F10 | 6 | 20 |\n| 51 | 604 | 612 | READ | 36 | P2:3 | F12 | 8 | 36 |\n| 52 | 616 | 618 | READ | 39 | P2:4 | F8 | 2 | 39 |\n\nTotal seek ticks: 564. Final arm position: sector 39.\n\n---\n\n## 5. Complete Eviction Log\n\n35 evictions over the simulation. Each eviction uses Enhanced Second Chance (lowest class, oldest load_tick, lowest frame number) with minimum-residency soft floor. After P3 terminates at tick 523, P3's frames become freely evictable (soft floor does not protect terminated processes).\n\n| Tick | Frame | Owner:VPN | R | D | Class | Reason |\n|------|-------|-----------|---|---|-------|--------|\n| 24 | F6 | P1:0 | 0 | 0 | C0 | P3:page1 needs frame |\n| 60 | F7 | P2:0 | 0 | 0 | C0 | P5:page1 needs frame |\n| 69 | F8 | P4:0 | 0 | 0 | C0 | P1:page2 needs frame |\n| 76 | F9 | P5:0 | 0 | 0 | C0 | P2:page15 needs frame |\n| 81 | F11 | P3:0 | 0 | 1 | C1 | P4:page1; dirty writeback |\n| 96 | F6 | P3:1 | 1 | 0 | C2 | P3:page2 needs frame |\n| 116 | F7 | P5:1 | 1 | 0 | C2 | P5:page2 needs frame |\n| 125 | F8 | P1:2 | 1 | 0 | C2 | P1:page3 needs frame |\n| 132 | F12 | P2:14 | 1 | 1 | C3 | P2:page1; dirty writeback |\n| 153 | F10 | P1:1 | 1 | 1 | C3 | P3:page3; dirty writeback |\n| 173 | F7 | P5:2 | 1 | 0 | C2 | P5:page3 needs frame |\n| 182 | F8 | P1:3 | 1 | 0 | C2 | P1:page4 needs frame |\n| 221 | F11 | P4:1 | 1 | 0 | C2 | P4:page2 needs frame |\n| 244 | F9 | P2:15 | 1 | 1 | C3 | P5:page4; dirty writeback |\n| 253 | F12 | P2:1 | 1 | 0 | C2 | P1:page1 reload |\n| 255 | F6 | P3:2 | 1 | 1 | C3 | P2:page1; dirty writeback |\n| 272 | F7 | P5:3 | 1 | 1 | C3 | P4:page3; dirty writeback |\n| 278 | F10 | P3:3 | 1 | 0 | C2 | P3:page4 needs frame |\n| 306 | F12 | P1:1 | 1 | 0 | C2 | P1:page5 needs frame |\n| 363 | F10 | P3:4 | 1 | 0 | C2 | P3:page5 needs frame |\n| 383 | F8 | P1:4 | 1 | 1 | C3 | P5:page5; dirty writeback |\n| 392 | F12 | P1:5 | 1 | 0 | C2 | P1:page6 needs frame |\n| 396 | F6 | P2:1 | 1 | 0 | C2 | P2:page2 needs frame |\n| 411 | F7 | P4:3 | 1 | 0 | C2 | P4:page15 needs frame |\n| 416 | F11 | P4:2 | 1 | 1 | C3 | P3:page6; dirty writeback |\n| 436 | F6 | P2:2 | 1 | 0 | C2 | P1:page0 reload |\n| 438 | F7 | P4:15 | 1 | 0 | C2 | P2:page2 reload |\n| 440 | F9 | P5:4 | 1 | 1 | C3 | P4:page15 reload; dirty writeback |\n| 479 | F6 | P1:0 | 1 | 0 | C2 | P1:page7 needs frame |\n| 481 | F8 | P5:5 | 1 | 0 | C2 | P5:page0 reload |\n| 490 | F7 | P2:2 | 1 | 0 | C2 | P2:page14 reload |\n| 537 | F11 | P3:6 | 1 | 0 | C2 | P1:page8 needs frame; P3 terminated |\n| 555 | F10 | P3:5 | 1 | 1 | C3 | P5:page6 needs frame; P3 terminated; dirty writeback |\n| 559 | F12 | P1:6 | 1 | 1 | C3 | P2:page3; dirty writeback |\n| 616 | F8 | P5:0 | 1 | 0 | C2 | P2:page4 needs frame |\n\n---\n\n## 6. Per-Process Execution Summary\n\n### P1 (11 operations, 11 page faults, 0 COW)\n\n| Op# | Instruction | Tick Start | Event | Frame |\n|-----|------------|------------|-------|-------|\n| 0 | R(0) | 0 | Page fault → F6 (loaded tick 7) | F6 |\n| 0 | R(0) | 9 | TLB miss walk; interrupted by fork at tick 10 | F6 |\n| 0 | R(0) | 12–13 | TLB miss walk+access (restart after fork) | F6 |\n| 1 | W(1) | 14 | Page fault → F10 (loaded tick 65) | F10 |\n| 2 | R(2) | 69 | Page fault → F8 (loaded tick 121); evicts P4:0 | F8 |\n| 3 | R(3) | 125 | Page fault → F8 (loaded tick 178); evicts P1:2 | F8 |\n| 4 | W(4) | 182 | Page fault → F8 (loaded tick 249); evicts P1:3 | F8 |\n| 5 | R(1) | 253 | Page fault → F12 (loaded tick 302); reload | F12 |\n| 6 | R(5) | 306 | Page fault → F12 (loaded tick 388); evicts P1:1 | F12 |\n| 7 | W(6) | 392 | Page fault → F12 (loaded tick 432); evicts P1:5 | F12 |\n| 8 | R(0) | 436 | Page fault → F6 (loaded tick 475); reload | F6 |\n| 9 | W(7) | 479 | Page fault → F6 (loaded tick 533); evicts P1:0 | F6 |\n| 10 | R(8) | 537 | Page fault → F11 (loaded tick 573); evicts P3:6 | F11 |\n\nP1 completes at **tick 576** after R(8) TLB miss access completes.\n\n### P2 (9 operations, 10 page faults, 0 COW)\n\n| Op# | Instruction | Key Event |\n|-----|------------|-----------|\n| 0 | R(0) | PF tick 2 → F7 (loaded tick 15) |\n| 1 | R(14) | PF tick 20 → F12 (loaded tick 72). Shared mmap established |\n| 2 | W(15) | PF tick 76 → F9 (loaded tick 128). Shared VPN 15 |\n| 3 | R(1) | PF tick 132. Dirty evict F12, WB wait. Loaded tick 252 into F12. Evicted at tick 253 by P1! PF again tick 255. Dirty evict F6, WB wait. Loaded tick 390 into F6 |\n| 4 | R(2) | PF tick 396 → F6 (loaded tick 434). Evicted at tick 436! PF again tick 438 → F7 (loaded tick 486) |\n| 5 | W(14) | PF tick 490 → F7 (loaded tick 554). Reload shared VPN 14 |\n| 6 | R(3) | PF tick 559. Dirty evict F12, WB wait. Loaded tick 612 into F12 |\n| 7 | W(4) | PF tick 616 → F8 (loaded tick 618); evicts P5:0 |\n| 8 | R(14) | TLB miss ticks 622–623. Resident in F7. No page fault |\n\nP2 has 10 page faults because R(1) and R(2) each fault twice (pages evicted between first load and access). P2 completes at **tick 623**.\n\n### P3 (7 operations, 6 page faults, 1 COW)\n\n| Op# | Instruction | Key Event |\n|-----|------------|-----------|\n| 0 | W(0) | COW fault tick 16. F11 allocated immediately. 2 kernel ticks at ticks 22–23 |\n| 1 | R(1) | PF tick 24 → F6 (loaded tick 92) |\n| 2 | W(2) | PF tick 96 → F6 (loaded tick 149) |\n| 3 | R(3) | PF tick 153 → F10 (loaded tick 274) |\n| 4 | R(4) | PF tick 278 → F10 (loaded tick 359) |\n| 5 | W(5) | PF tick 363 → F10 (loaded tick 412) |\n| 6 | R(6) | PF tick 416 → F11 (loaded tick 520) |\n\nP3 completes at **tick 523**. First to finish — shortest program and COW resolved quickly.\n\n### P4 (8 operations, 7 page faults, 0 COW)\n\n| Op# | Instruction | Key Event |\n|-----|------------|-----------|\n| 0 | R(0) | PF tick 4 → F8 (loaded tick 29) |\n| 1 | R(14) | PF tick 33 (mmap piggyback on P2's F12 page-in, loaded tick 72) |\n| 2 | W(14) | TLB hit tick 80. The only TLB hit in the simulation |\n| 3 | R(1) | PF tick 81 → F11 (loaded tick 215); dirty evict P3:0 |\n| 4 | R(15) | TLB miss ticks 219–220. Attaches to shared F9 (loaded by P2) |\n| 5 | W(2) | PF tick 221 → F11 (loaded tick 268) |\n| 6 | R(3) | PF tick 272 → F7 (loaded tick 407) |\n| 7 | W(15) | PF tick 411 → F7 (loaded tick 436). Evicted at tick 438! PF again tick 440. Dirty evict F9, WB wait. Loaded tick 570 into F9 |\n\nP4 completes at **tick 573**.\n\n### P5 (8 operations, 8 page faults, 0 COW)\n\n| Op# | Instruction | Key Event |\n|-----|------------|-----------|\n| 0 | R(0) | PF tick 6 → F9 (loaded tick 56) |\n| 1 | R(1) | PF tick 60 → F7 (loaded tick 112) |\n| 2 | R(2) | PF tick 116 → F7 (loaded tick 169) |\n| 3 | W(3) | PF tick 173 → F7 (loaded tick 240) |\n| 4 | W(4) | PF tick 244 → F9. Dirty evict P2:15, WB wait. Loaded tick 379 |\n| 5 | R(5) | PF tick 383 → F8. Dirty evict P1:4, WB wait. Loaded tick 472 |\n| 6 | R(0) | PF tick 481 → F8 (loaded tick 551). Reload page 0 |\n| 7 | W(6) | PF tick 555 → F10. Dirty evict P3:5, WB wait. Loaded tick 603 |\n\nP5 completes at **tick 606**.\n\n---\n\n## 7. Context-Switch Breakdown\n\n83 total context switches. The tick-0 first dispatch is free and not counted.\n\nBreakdown by type:\n\n- Process → Process: 15 transitions (e.g., CS #1 P1→P2, CS #9 P3→P2, CS #64 P5→P1, ...)\n- Process → IDLE: 34 transitions (every page fault that leaves no READY process)\n- IDLE → Process: 34 transitions (each unblock from an idle state)\n\n10 quantum expiries trigger scheduling re-evaluation. In 9 of these, the expired process is the only candidate and is re-dispatched without a context switch. At tick 476, P5 expires but P1 (newly unblocked) has a lower PID and is selected, producing CS #64.\n\n---\n\n## 8. Dirty Writeback Summary\n\n11 dirty writebacks occurred when evicting frames with D=1:\n\n| Tick Evicted | Frame | Content | Sector | WB Begin | WB Done |\n|-------------|-------|---------|--------|----------|---------|\n| 81 | F11 | P3:0 | 40 | 129 | 145 |\n| 132 | F12 | P2:14 | 5 | 179 | 188 |\n| 153 | F10 | P1:1 | 17 | 216 | 236 |\n| 244 | F9 | P2:15 | 8 | 275 | 296 |\n| 255 | F6 | P3:2 | 46 | 303 | 318 |\n| 272 | F7 | P5:3 | 11 | 319 | 337 |\n| 383 | F8 | P1:4 | 26 | 413 | 428 |\n| 416 | F11 | P4:2 | 59 | 437 | 450 |\n| 440 | F9 | P5:4 | 14 | 487 | 497 |\n| 555 | F10 | P3:5 | 55 | 574 | 583 |\n| 559 | F12 | P1:6 | 32 | 584 | 596 |\n\n---\n\n## 9. Final State at Tick 623\n\n### Frame Map\n\n| Frame | Contents |\n|-------|----------|\n| F1 | PT:P1 |\n| F2 | PT:P2 |\n| F3 | PT:P4 |\n| F4 | PT:P3 |\n| F5 | PT:P5 |\n| F6 | P1:7 |\n| F7 | P2:14 |\n| F8 | P2:4 |\n| F9 | P4:15 |\n| F10 | P5:6 |\n| F11 | P1:8 |\n| F12 | P2:3 |\n\n### Completion Order\n\n| Rank | Process | Tick |\n|------|---------|------|\n| 1st | P3 | 523 |\n| 2nd | P4 | 573 |\n| 3rd | P1 | 576 |\n| 4th | P5 | 606 |\n| 5th | P2 | 623 |\n\n---\n\n## 10. Required Output\n\n```text\npage_faults=11,10,6,7,8\ntlb_hits=1\ncontext_switches=83\ncow_faults=1\ndirty_writebacks=11\ntotal_seek_ticks=564\ndisk_arm_final=39\ncompletion_order=3,4,1,5,2\np3_first_cow_tick=16\nlast_tick=623\nfinal_frame_map=F1:PT:P1,F2:PT:P2,F3:PT:P4,F4:PT:P3,F5:PT:P5,F6:P1:7,F7:P2:14,F8:P2:4,F9:P4:15,F10:P5:6,F11:P1:8,F12:P2:3\n```\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given a permutation `p` of `{1, 2, ..., n}`. It is **not** sorted in ascending order and **not** sorted in descending order.\n\nInitially, all elements are colored **red**. Players alternate turns. On each turn, a player may do one of:\n\n1. **Rearrange** the permutation so that all **red** elements keep their positions (blue elements may be permuted arbitrarily).\n2. Change the color of **one** red element to **blue**.\n3. Skip the turn.\n\nThe **first** player wins if the permutation becomes `[1, 2, ..., n]`.\nThe **second** player wins if the permutation becomes `[n, n-1, ..., 1]`.\nIf the game lasts `100500` turns without a winner, it is a draw.\n\nDetermine the result under optimal play:\n- output **1** if the first player wins,\n- output **2** if the second player wins,\n- output **0** if it is a draw.\n\n### Input\n- `n` (`3 ≤ n ≤ 5·10^5`)\n- `p_1, ..., p_n`: a permutation of `1..n`, not fully ascending/descending\n\n### Output\nOne integer: `1`, `2`, or `0`.", "rubrics": [{"criterion": "Does the answer state that using the “rearrange while keeping red positions fixed” operation is only useful if it produces an immediate win on that same move (because the opponent can undo any non-winning rearrangement next move)?", "weight": 10}, {"criterion": "Does the answer define the set of indices needed for the first player (ascending) as S_asc = { i | p[i] ≠ i}?", "weight": 10}, {"criterion": "Does the answer define the set of indices needed for the second player (descending) as S_desc = { i | p[i] ≠ n−i+1}?", "weight": 10}, {"criterion": "Does the answer define a as the count of indices only the first player needs to make blue, i.e., a = |S_asc \\\\ S_desc|?", "weight": 10}, {"criterion": "Does the answer define b as the count of indices only the second player needs to make blue, i.e., b = |S_desc \\\\ S_asc|?", "weight": 10}, {"criterion": "Does the answer define c as the count of indices both players need to make blue, i.e., c = |S_asc ∩ S_desc|?", "weight": 10}, {"criterion": "Does the answer state the first player winning condition as a + c ≤ b?", "weight": 20}, {"criterion": "Does the answer state the second player winning condition as b + c < a?", "weight": 10}, {"criterion": "Does the answer state the final decision rule: output 1 if (a+c ≤ b), else output 2 if (b+c < a), otherwise output 0?", "weight": 10}], "golden_answer": "### Expert Solution\n\nA “rearrange (keeping red positions fixed)” move is only useful if it produces an **immediate win** on that move; otherwise the opponent can undo any non-winning rearrangement on their next move because the set of fixed (red) positions hasn’t changed.\n\nSo the game reduces to a race to recolor enough positions to **blue** so that a winning permutation can be formed by permuting only blue positions.\n\n---\n\n## Required-blue index sets\n\n- To reach ascending `[1, 2, ..., n]`, any index `i` with `p_i ≠ i` must become blue (a red mismatch can never be fixed):\n `S_asc = { i | p_i ≠ i }`\n\n- To reach descending `[n, n-1, ..., 1]`, any index `i` with `p_i ≠ (n - i + 1)` must become blue:\n `S_desc = { i | p_i ≠ (n - i + 1) }`\n\nPartition into counts:\n- `a = |S_asc \\ S_desc|`\n- `b = |S_desc \\ S_asc|`\n- `c = |S_asc ∩ S_desc|`\n\n---\n\n## Optimal-play outcome\n\n- First player wins iff:\n `a + c ≤ b`\n\n- Second player wins iff:\n `b + c < a`\n\n- Otherwise neither can force a win, so the result is a draw.\n\n**Output rule:**\n- if `a + c ≤ b` output **1**\n- else if `b + c < a` output **2**\n- else output **0**\n\nAll counts are computed in one pass over `i = 1..n` in `O(n)`."}
{"domain": "Algorithms & Data Structures", "prompt": "Let `a` and `b` be two arrays of lengths `n` and `m`, with no elements in common. Define `merge(a, b)` recursively:\n\n- `merge(∅, b) = b` and `merge(a, ∅) = a`.\n- If both are non-empty and `a_1 < b_1`, then\n `merge(a, b) = [a_1] + merge([a_2, ..., a_n], b)`.\n- If both are non-empty and `a_1 > b_1`, then\n `merge(a, b) = [b_1] + merge(a, [b_2, ..., b_m])`.\n\nYou are given a permutation `p` of length `2n` (it contains each integer `1` to `2n` exactly once). Determine if there exist two arrays `a` and `b`, each of length `n` and with no common elements, such that:\n`p = merge(a, b)`\n\n### Input\n- `n` (`1 ≤ n ≤ 2000`)\n- `p_1, ..., p_{2n}`: a permutation of `1, ..., 2n`\n\n### Output\nPrint **YES** if such arrays `a, b` exist, otherwise print **NO**.", "rubrics": [{"criterion": "Does the answer state that merge outputs the smaller of the two current first elements (a1 vs b1) when both arrays are non-empty?", "weight": 10}, {"criterion": "Does the answer define the block starts as indices i where p[i] is a new prefix maximum (p[i] > all previous p[1..i-1])?", "weight": 10}, {"criterion": "Does the answer state that these prefix-maximum indices partition p into contiguous blocks (segments)?", "weight": 10}, {"criterion": "Does the answer describe how to compute each block length from consecutive block-start indices (and the last block to the end)?", "weight": 10}, {"criterion": "Does the answer explicitly state that the block lengths add up to 2n?", "weight": 10}, {"criterion": "Does the answer state the check to perform as: whether some subset of block lengths sums to n?", "weight": 10}, {"criterion": "Does the answer define dp[s] as a boolean meaning “some subset of processed blocks has total length s”?", "weight": 10}, {"criterion": "Does the answer include the DP initialization dp[0] = true?", "weight": 10}, {"criterion": "Does the answer give the DP update for each block length L as setting dp[s+L] = true when dp[s] is true (i.e., subset-sum transition)?", "weight": 10}, {"criterion": "Does the answer state the final decision rule: print YES iff dp[n] is true, else NO, and state time complexity O(n^2)?", "weight": 10}], "golden_answer": "### Expert Solution\n\nIn `merge(a, b)`, whenever both arrays are non-empty, the next output element is `min(a_1, b_1)`, and that element is removed from its array.\n\n---\n\n## 1) Key lemma (using the maximum)\n\nLet `M` be the **maximum** value among the elements that have not yet been output.\nAssume `M` is currently the first element of one array (say it belongs to `a`).\n\nSince all values are distinct, `M` is larger than every remaining element of `b`.\nSo while `b` is non-empty, `min(a_1, b_1)` cannot be `M`; merge must keep outputting elements from `b` until `b` becomes empty, and **only then** can it output `M`.\n\nTherefore, in the final permutation `p`, the position where the current maximum `M` appears begins a **contiguous suffix** that must come entirely from the array containing `M`.\n\n---\n\n## 2) Blocks from prefix maxima\n\nRepeatedly removing such suffixes partitions `p` into contiguous blocks.\n\nEquivalently, the **block starts** are exactly the indices `i` where `p_i` is a new prefix maximum:\n`p_i > max(p_1, ..., p_{i-1})`\n\nLet these indices be `i_1 < i_2 < ... < i_k` (with `i_1 = 1`).\nThen the block lengths are:\n- `L_1 = i_2 - i_1`\n- `L_2 = i_3 - i_2`\n- ...\n- `L_{k-1} = i_k - i_{k-1}`\n- `L_k = 2n - i_k + 1`\n\nThey sum to `2n`, and each block must be assigned wholly to either `a` or `b`.\n\n---\n\n## 3) Reduction to subset sum\n\nSince `|a| = |b| = n`, we need to choose a subset of block lengths whose sum is exactly `n`\n(the remaining blocks then sum to `n` automatically).\n\n- This is **necessary** because blocks cannot be split between arrays.\n- This is **sufficient** because assigning whole blocks to `a` and `b` makes merge reproduce `p` block-by-block by the lemma above.\n\n---\n\n## 4) DP\n\nSubset-sum DP:\n\n- `dp[s]` = whether we can reach total length `s`\n- Initialize `dp[0] = true`\n- For each block length `L`, for `s` from `n - L` down to `0`:\n `dp[s + L] |= dp[s]`\n\nOutput **YES** iff `dp[n]` is true, else **NO**.\n\n---\n\n## 5) Complexity\n\nAt most `2n` blocks and `n ≤ 2000`, so the DP is:\n`O(n^2)`\ntime and `O(n)` memory."}
{"domain": "Algorithms & Data Structures", "prompt": "Given integers n, m, and v, consider all n x m matrices whose entries are integers in [1, v].\n\nA matrix a is called **friendly** if:\n\n min_{1 <= i <= n} ( max_{1 <= j <= m} a_{i,j} ) <= max_{1 <= j <= m} ( min_{1 <= i <= n} a_{i,j} )\n\nIn words:\n- For each row, compute its maximum element. Take the minimum of these row-maximums.\n- For each column, compute its minimum element. Take the maximum of these column-minimums.\n- The matrix is friendly if the first quantity is less than or equal to the second.\n\n**Task:** For each test case, compute the number of friendly n x m matrices with entries in [1, v], modulo 998244353.\n\nAdditionally, state the closed-form formula you use (in terms of n, m, v, and a summation variable k), and explain the key mathematical insight that enables an efficient O(n * v * log m) algorithm. Specifically:\n1. Why the friendly condition reduces to equality of the two quantities.\n2. What geometric structure the set of \"extremal\" positions forms.\n3. How the binomial theorem eliminates the inner summation over column subsets.\n\n**Input:**\n- First line: integer t (number of test cases).\n- Each test case: one line with three integers n, m, v.\n\n**Constraints:**\n- 1 <= t <= 5\n- 1 <= n <= 250\n- 1 <= m <= 10^9\n- 1 <= v <= 4000\n- n * v <= 10^6\n\n**Output:**\nFor each test case, output one integer: the count of friendly matrices modulo 998244353.\n\n**Test Input:**\n5\n2 2 2\n3 3 3\n2 1000000000 2\n3 4 5\n4 100 3", "rubrics": [{"criterion": "The response outputs 14 as the answer for the test case n=2, m=2, v=2.", "weight": 10}, {"criterion": "The response outputs 11463 as the answer for the test case n=3, m=3, v=3.", "weight": 10}, {"criterion": "The response outputs 123732870 as the answer for the test case n=2, m=1000000000, v=2.", "weight": 15}, {"criterion": "The response outputs 92839345 as the answer for the test case n=3, m=4, v=5.", "weight": 10}, {"criterion": "The response outputs 410518279 as the answer for the test case n=4, m=100, v=3.", "weight": 10}, {"criterion": "The response correctly explains that the friendly condition (min of row-maxes <= max of col-mins) holds if and only if the two quantities are equal, using the minimax inequality.", "weight": 10}, {"criterion": "The response identifies that the set of positions simultaneously achieving the row-maximum and column-minimum value k forms a complete subrectangle (i.e., a Cartesian product of a subset of rows and a subset of columns).", "weight": 10}, {"criterion": "The response applies the binomial theorem to collapse the summation over column subsets into a closed-form expression, eliminating the explicit loop over j.", "weight": 15}, {"criterion": "The response states that the overall time complexity is O(n * v * log m) per test case.", "weight": 10}], "golden_answer": "We count n x m matrices with entries in [1, v] satisfying:\n min_i(max_j a[i][j]) <= max_j(min_i a[i][j])\n\n\n1. Reduction to Equality\n\n\nLet L = min_i(max_j a[i][j]) achieved at row r1, and\n R = max_j(min_i a[i][j]) achieved at column c1.\n\nConsider cell (r1, c1):\n- a[r1][c1] <= max_j a[r1][j] = L (since L is the max of row r1)\n- a[r1][c1] >= min_i a[i][c1] >= R (wait, min_i a[i][c1] is the column min, and R is the max of column mins)\n\nActually more carefully:\n- L = max_j a[r1][j], so a[r1][c1] <= L.\n- min_i a[i][c1] <= a[r1][c1], and R = max_j(min_i a[i][j]) >= min_i a[i][c1].\n\nThis gives us: L >= a[r1][c1] >= min_i a[i][c1], and\nindependently R >= min_i a[i][c1].\n\nThe key fact is the minimax inequality: for any matrix,\n min_i(max_j a[i][j]) >= max_j(min_i a[i][j])\n\nProof: For any row i and column j, max_j' a[i][j'] >= a[i][j] >= min_i' a[i'][j].\nTaking min over i on the left and max over j on the right gives L >= R.\n\nTherefore the friendly condition L <= R combined with L >= R gives L = R.\nThe matrix is friendly if and only if the two quantities are equal.\n\n\n2. Structure: Extremal Positions Form a Subrectangle\n\n\nFix a value k in [1, v]. Consider positions (i, j) where:\n- a[i][j] = k\n- k is the maximum of row i (so all entries in row i are <= k)\n- k is the minimum of column j (so all entries in column j are >= k)\n\nClaim: these positions form a complete (combinatorial) subrectangle.\n\nProof: Take (r1, c1) and (r2, c2) both in this set with r1 != r2, c1 != c2.\nConsider (r1, c2):\n- Row r1 has max = k, so a[r1][c2] <= k.\n- Column c2 has min = k (from (r2, c2)), so a[r1][c2] >= k.\nThus a[r1][c2] = k, and (r1, c2) is also in the set.\n\nBy induction, if the set involves rows R and columns C, then every\n(r, c) with r in R, c in C is in the set. So the set is an\n|R| x |C| complete subrectangle.\n\n\n3. Counting via Inclusion-Exclusion\n\n\nFix k, and choose i rows and j columns to form the subrectangle.\n\nCell constraints:\n- Inside the subrectangle (i*j cells): fixed to k.\n- Chosen rows, outside chosen columns (i*(m-j) cells): must be <= k, so k choices each.\n- Chosen columns, outside chosen rows ((n-i)*j cells): must be >= k, so (v-k+1) choices each.\n- Remaining cells ((n-i)*(m-j) cells): unrestricted, v choices each.\n\nTo ensure at least 1 row and at least 1 column, apply inclusion-exclusion:\n\n sum_{k=1}^{v} sum_{i=1}^{n} sum_{j=1}^{m}\n (-1)^{i+j} * C(n,i) * C(m,j)\n * k^{i*(m-j)}\n * (v-k+1)^{(n-i)*j}\n * v^{(n-i)*(m-j)}\n\n\n4. Binomial Theorem Eliminates the j-Loop\n\n\nFor fixed i, rewrite the sum over j (extending to j=0 then subtracting):\n\n sum_{j=0}^{m} C(m,j) * [-(v-k+1)^{n-i}]^j * [k^i * v^{n-i}]^{m-j}\n\nBy the binomial theorem this equals:\n\n (k^i * v^{n-i} - (v-k+1)^{n-i})^m\n\nSubtracting the j=0 term [k^i * v^{n-i}]^m, the final formula is:\n\n answer = sum_{k=1}^{v} sum_{i=1}^{n}\n (-1)^i * C(n,i) * [ (k^i * v^{n-i} - (v-k+1)^{n-i})^m - (k^i * v^{n-i})^m ]\n\nAll exponentiations use fast modular exponentiation (mod 998244353).\n\n\n5. Complexity\n\n\n- k ranges over v values, i ranges over n values.\n- Each term requires O(log m) for modular exponentiation.\n- Total: O(n * v * log m).\n- Since n*v <= 10^6 and log m <= 30, this is efficient.\n\n\n6. Verification Code (Python)\n\n\n```python\nimport sys\nfrom math import comb\n\nMOD = 998244353\n\ndef solve(n, m, v):\n ans = 0\n for k in range(1, v + 1):\n for i in range(1, n + 1):\n sign = (-1) ** i\n c = comb(n, i) % MOD\n A = pow(k, i, MOD) * pow(v, n - i, MOD) % MOD # k^i * v^{n-i}\n B = pow(v - k + 1, n - i, MOD) # (v-k+1)^{n-i}\n base = (A - B) % MOD\n term = sign * c % MOD * ((pow(base, m, MOD) - pow(A, m, MOD)) % MOD) % MOD\n ans = (ans + term) % MOD\n return ans % MOD\n\nt = int(input())\nfor _ in range(t):\n n, m, v = map(int, input().split())\n print(solve(n, m, v))\n```\n\n\n7. Test Case Verification\n\n\nInput:\n5\n2 2 2\n3 3 3\n2 1000000000 2\n3 4 5\n4 100 3\n\nOutput:\n14 (brute-force verified: 14 out of 16 matrices are friendly)\n11463 (brute-force verified: 11463 out of 19683 matrices)\n123732870 (requires modular exponentiation)\n92839345\n410518279\n\nThe first two outputs were independently verified by brute-force enumeration."}
{"domain": "Algorithms & Data Structures", "prompt": "## Reach a Regular Bracket Sequence by Flipping Equal Adjacent Pairs\n\nYou are given a bracket string `s` of length `n` consisting only of characters `(` and `)`.\n\nYou may apply the following operations any number of times (possibly zero), in any order:\n\n1. Choose an index `i` (`1 ≤ i < n`) such that `s[i] = s[i+1] = '('`, and replace both characters with `')'`.\n2. Choose an index `i` (`1 ≤ i < n`) such that `s[i] = s[i+1] = ')'`, and replace both characters with `'('`.\n\nFor each test case, output any **regular bracket sequence** `t` that can be obtained from `s` by these operations, or output `-1` if it is impossible.\n\nA bracket sequence is **regular** iff it is a correct bracket sequence (balanced and every prefix has at least as many `(` as `)`).\n\n### Input\nMultiple test cases:\n- First line: `t` — number of test cases (`1 ≤ t ≤ 10^4`)\nFor each test case:\n- Line 1: integer `n` (`1 ≤ n ≤ 2·10^5`)\n- Line 2: string `s` of length `n`\n\nIt is guaranteed that the sum of `n` over all test cases does not exceed `2·10^5`.\n\n### Output\nFor each test case, print a regular bracket sequence `t` obtainable from `s`, or `-1`.\n", "rubrics": [{"criterion": "The answer defines a transformation that flips the bracket character on every even position of the string.", "weight": 10}, {"criterion": "The answer states that in the transformed string the operation can rewrite the substring \\\"()\\\" into \\\")(\\\".", "weight": 10}, {"criterion": "The answer states that in the transformed string the operation can rewrite the substring \\\")(\\\" into \\\"()\\\".", "weight": 10}, {"criterion": "The answer states that if n is odd then the output is −1.", "weight": 10}, {"criterion": "The answer states that a necessary feasibility condition is that the number of '(' characters in the transformed string is even.", "weight": 10}, {"criterion": "The answer states that the transformed operations allow reaching any permutation of the transformed string’s characters.", "weight": 10}, {"criterion": "The answer states that if the transformed string contains zero '(' characters then it is impossible to obtain a regular bracket sequence.", "weight": 10}, {"criterion": "The answer defines x as open/2 where open is the number of '(' characters in the transformed string.", "weight": 10}, {"criterion": "The answer gives an explicit construction of t as \\\"()\\\" repeated (x−1) times, followed by \\\"(\\\", followed by \\\"()\\\" repeated (n/2−x) times, followed by \\\")\\\".", "weight": 10}, {"criterion": "The answer states a per-test-case time complexity of O(n)", "weight": 10}], "golden_answer": "## Expert Solution\n\n### 1) Key transformation: flip even positions\n\nDefine a transformed string `s'` (1-indexed) by flipping the bracket on every even position:\n- if `s[i] = '('` then `s'[i] = ')'` for even `i`\n- if `s[i] = ')'` then `s'[i] = '('` for even `i`\n- odd positions stay unchanged\n\nThis transformation is invertible (apply it again to return to the original domain).\n\n---\n\n### 2) Operations become adjacent swaps in the transformed string\n\nConsider an operation on equal adjacent brackets in `s`:\n\n- If `s[i]=s[i+1]='('`, after flipping even positions the pair becomes either `\"()\"` or `\")(\"` (depending on parity of `i`).\n After the operation the pair becomes `\"))\"`, which flips to the opposite mixed pair.\n- Similarly, `\"))\"` operations also flip between `\"()\"` and `\")(\"`.\n\nTherefore, in `s'` the operation is exactly:\n\\[\n\"()\" \\leftrightarrow \")(\"\n\\]\nwhich is an adjacent swap of two different characters.\n\nHence, using these operations we can perform arbitrary adjacent swaps in `s'`, so we can reach **any permutation of `s'`**. \nEquivalently, the only invariant is the multiset of characters, i.e. the number of `'('` in `s'`.\n\nLet:\n- `open = count('(' in s')`.\n\nThen `s` can reach a target `t` iff `s'` can be permuted into `t'` where `t'` is `t` with even positions flipped, which holds iff `t'` has exactly `open` opening brackets.\n\n---\n\n### 3) Characterize when a regular bracket sequence is possible\n\nA regular bracket sequence must have even length, so if `n` is odd the answer is `-1`.\n\nAlso, for any regular bracket sequence `t`, after flipping even positions the number of `'('` in `t'` is always even (it equals `2 * (# of '(' on odd positions in t)`).\nSo we must have `open` even.\n\nIf `open = 0`, then `t'` has no `'('`, which is impossible for any regular bracket sequence `t` (the first character of `t` must be `'('` and position 1 is not flipped). \nSo we also need `open >= 2`.\n\nThus feasibility conditions are:\n- `n` is even\n- `open` is even\n- `open > 0` (equivalently `open >= 2`)\n\nIf any fails, print `-1`.\n\n---\n\n### 4) Construct a regular bracket sequence with a prescribed `open`\n\nLet `open = count('(' in s')` and define:\n\\[\nx = open/2.\n\\]\nWe construct a regular bracket sequence `t` of length `n` such that after flipping even positions, `t'` has exactly `open` opening brackets.\n\nConstruction:\n- Output `\"()\"` repeated `(x-1)` times\n- Then output `\"(\"`\n- Then output `\"()\"` repeated `(n/2 - x)` times\n- Then output `\")\"`\n\nFormally:\n\\[\nt = \\underbrace{()() \\dots ()}_{x-1\\ \\text{times}} \\; + \\; ( \\; + \\; \\underbrace{()() \\dots ()}_{(n/2-x)\\ \\text{times}} \\; + \\; )\n\\]\n\nThis is a concatenation of regular bracket sequences, so `t` is regular.\n\nBy construction, the number of `'('` on odd positions in `t` is exactly `x`, hence `t'` has `2x = open` opening brackets.\n\nSince `s'` can be permuted into any string with the same number of `'('`, we can permute `s'` into `t'`, and applying the inverse flip yields `t` obtainable from `s`.\n\nOutput `t`.\n\n---\n\n### 5) Complexity\n\nFor each test case:\n- building `s'` and counting `open`: `O(n)`\n- constructing `t`: `O(n)`\n\nTotal over all test cases: `O(sum n)`.\n"}
{"domain": "Database Systems & Data Engineering", "prompt": "A database system executes concurrent transactions under Snapshot Isolation (SI). The system must detect write-skew anomalies and compute conflict metrics.\n\nCRITICAL CLARIFICATION: All reads occur instantaneously at the transaction's start time (SI snapshot semantics).\n\nTransaction Schedule (10 transactions):\nT1: R(X)10 R(Y)20 W(X)30\nT2: R(Y)20 R(Z)15 W(Y)40\nT3: R(X)10 R(Z)15 W(Z)25\nT4: R(Z)25 R(Y)40 W(X)50\nT5: R(X)30 R(Y)40 W(Y)60\nT6: R(Y)60 R(Z)25 W(Z)35\nT7: R(Z)35 R(X)50 W(X)70\nT8: R(X)70 R(Y)60 W(Y)80\nT9: R(Y)80 R(Z)35 W(Z)45\nT10: R(Z)45 R(X)70 W(X)90\n\nNotation: R(X)v means \"Read variable X with value v\", W(X)v means \"Write variable X with value v\"\n\nExecution Timeline (timestamp order):\nT1: [0,15], T2: [5,20], T3: [10,25], T4: [12,30], T5: [18,35]\nT6: [22,40], T7: [28,45], T8: [33,50], T9: [38,55], T10: [42,60]\n\nFormat: [start_time, commit_time] in milliseconds\n\nConflict Detection Rules:\n\n1. Write-Read (WR) Conflict: Ti writes X at value v, Tj reads X with value u where u ≠ v, and Ti commits before Tj starts\n2. Read-Write (RW) Conflict: Ti reads X with value v, Tj writes X with value u where u ≠ v, and start_time(Ti) ∈ [start_time(Tj), commit_time(Tj)]\n3. Write-Write (WW) Conflict: Ti writes X at value v, Tj writes X with value u where u ≠ v, and their execution windows overlap\n\nAnalysis Requirements:\n\nPhase 1: Conflict Graph Construction\nFor each conflict type (WR, RW, WW), identify all pairs (Ti, Tj) that satisfy the conflict condition.\n\nPhase 2: Conflict Metric Calculation\nFor each detected conflict (Ti, Tj):\n\nStep 1: Compute Temporal Distance (TD):\nTD = |commit_time(Ti) - start_time(Tj)|\n\nStep 2: Compute Value Divergence (VD):\n- Let Vi be the set of all values written by Ti\n- Let Vj be the set of all values written by Tj\n- VD = Σ|vi - vj| for all pairs (vi, vj) where vi ∈ Vi and vj ∈ Vj\n\nStep 3: Compute Conflict Hash (CH):\nCH = (i × 1000 + j × 100 + TD) mod 997\n\nStep 4: Compute Prime Factor Sum (PFS):\n- Factorize CH into prime factors\n- If CH is prime, PFS = CH\n- Otherwise, PFS = sum of all prime factors (with repetition)\n\nStep 5: Update Cumulative Conflict Score (CCS):\nCCS = CCS + (PFS × VD / 100)\nInitially, CCS = 0.\n\nPhase 3: Serializability Analysis\nA cycle exists in the conflict graph if there is a path Ti → Tj → ... → Tk → Ti.\nCount all simple cycles (no repeated transactions except start/end).\n\nRequired Outputs:\n\n1. Total_WR_Conflicts: Count of Write-Read conflicts\n2. Total_RW_Conflicts: Count of Read-Write conflicts\n3. Total_WW_Conflicts: Count of Write-Write conflicts\n4. Final_CCS: Cumulative Conflict Score rounded to 2 decimal places\n5. Total_Cycles: Number of simple cycles in the conflict graph\n6. Largest_Cycle_Length: Length (number of transactions) in the longest cycle\n7. Is_Serializable: \"YES\" if no cycles exist, \"NO\" otherwise\n\nProvide your answer in exactly this format:\nTotal_WR_Conflicts: [integer]\nTotal_RW_Conflicts: [integer]\nTotal_WW_Conflicts: [integer]\nFinal_CCS: [decimal with 2 places]\nTotal_Cycles: [integer]\nLargest_Cycle_Length: [integer]\nIs_Serializable: [YES/NO]", "rubrics": [{"criterion": "Does the answer treat all reads as instantaneous events occurring strictly at start_time(Ti) and not over the transaction’s execution window?", "weight": 10}, {"criterion": "Does the answer conclude Total_WR_Conflicts = 0 by explicitly applying the condition that a WR conflict requires u ≠ v under snapshot isolation?", "weight": 10}, {"criterion": "Does the answer identify RW conflicts only when start_time(Ti) ∈ [start_time(Tj), commit_time(Tj)] and not based on transaction lifetime overlap?", "weight": 10}, {"criterion": "Does the answer correctly compute Value Divergence (VD) for each conflict as the absolute difference between the values written by Ti and Tj?", "weight": 10}, {"criterion": "Does the answer correctly compute and report Final_CCS as 132.48 after summing all conflict contributions?", "weight": 10}, {"criterion": "Does the answer compute Temporal Distance using the exact formula TD = |commit_time(Ti) − start_time(Tj)| for every conflict?", "weight": 20}, {"criterion": "Does the answer correctly report Total_Cycles = 0 and Largest_Cycle_Length = 0 based on the constructed graph?", "weight": 10}, {"criterion": "Does the answer identify exactly 7 Read–Write (RW) conflicts, neither omitting nor adding any pairs?", "weight": 10}, {"criterion": "Does the answer correctly report Is_Serializable as YES based on zero detected cycles?", "weight": 10}], "golden_answer": "## 1. Conflict Identification (Phase 1)\n\n### 1.1 Write–Read (WR) Conflicts\nUnder Snapshot Isolation, each transaction reads the most recent committed value strictly before its start time.\n\nFor a Write–Read (WR) conflict to exist, there must be a pair (Ti, Tj) such that:\n\n• Ti writes X = v\n• Ti commits before start_time(Tj)\n• Tj reads X = u\n• and u ≠ v\n\nFor every read operation in the schedule, the value read equals the value written by the last transaction that committed before the reader’s start time.\n\nTherefore, there is no pair (Ti, Tj) satisfying the value inequality condition (u ≠ v), and no WR conflicts occur.\n\n### 1.2 Read–Write (RW) Conflicts\n\nA Read–Write (RW) conflict exists if transaction (T_i) reads variable (X) at its start time, transaction (T_j) writes the same variable with a different value, and\n\nstart_time(T_i) ∈ [start_time(T_j), commit_time(T_j)].\n\nThe conflict edge direction is Ti → Tj (reader → writer).\n\nApplying this rule strictly:\n\n1. (T_4) reads (Z) at time 12 while (T_3) executes from 10 to 25 → (T_4 --> T_3)\n2. (T_5) reads (Y) at time 18 while (T_2) executes from 5 to 20 → (T_5 --> T_2)\n3. (T_6) reads (Z) at time 22 while (T_3) executes from 10 to 25 → (T_6 --> T_3)\n4. (T_7) reads (X) at time 28 while (T_4) executes from 12 to 30 → (T_7 --> T_4)\n5. (T_8) reads (Y) at time 33 while (T_5) executes from 18 to 35 → (T_8 --> T_5)\n6. (T_9) reads (Z) at time 38 while (T_6) executes from 22 to 40 → (T_9 --> T_6)\n7. (T_10) reads (X) at time 42 while (T_7) executes from 28 to 45 → (T_10 --> T_7)\n\nResult:\nTotal_RW_Conflicts = 7\n\n### 1.3 Write–Write (WW) Conflicts\n\nA Write–Write (WW) conflict exists if two transactions write the same variable with different values and their execution windows overlap. The edge direction is from the earlier writer to the later writer.\n\nIdentified conflicts:\n\nVariable X\n\n1. (T_1 --> T_4) (overlap [12,15])\n2. (T_4 --> T_7) (overlap [28,30])\n3. (T_7 --> T_10) (overlap [42,45])\n\nVariable Y\n4. (T_2 --> T_5) (overlap [18,20])\n5. (T_5 --> T_8) (overlap [33,35])\n\nVariable Z\n6. (T_3 --> T_6) (overlap [22,25])\n7. (T_6 --> T_9) (overlap [38,40])\n\nResult:\nTotal_WW_Conflicts = 7\n\n\n## 2. Conflict Metric Calculation (Phase 2)\n\nTotal conflicts:\n\n0(WR) + 7(RW) + 7(WW) = 14\n\nEach transaction writes exactly one value, so the Value Divergence (VD) is the absolute difference between the two written values.\n\n\n### 2.1 Example RW Conflict: (T_4 --> T_3)\n\n Temporal Distance \nTD = |commit_time(Ti) − start_time(Tj)|\n = |commit_time(T4) − start_time(T3)|\n = |30 − 10| = 20\n Value Divergence (VD): (|50 - 25| = 25)\n Conflict Hash (CH):\n ((4 x 1000 + 3 x 100 + 20) mod 997 = 332)\n Prime Factor Sum (PFS):\n (332 = 2^2 x 83 --> 2 + 2 + 83 = 87)\n CCS Increment:\n ((87 x 25)/100 = 21.75)\n\n\n### 2.2 Example WW Conflict: (T_1 --> T_4)\n\n TD: (|15 - 12| = 3)\n VD: (|30 - 50| = 20)\n CH:\n ((1 x 1000 + 4 x 100 + 3) mod 997 = 406)\n PFS:\n (406 = 2 x 7 x 29 --> 38)\n CCS Increment:\n ((38 x 20)/100 = 7.60)\n\n\n### 2.3 Final CCS\n\nSumming the CCS increments for all 14 conflicts:\n\nFinal_CCS = 132.48\n\n\n## 3. Serializability Analysis (Phase 3)\n\n### 3.1 Conflict Graph Edges\n\nWW edges (writer → writer):\n\n (T_1 --> T_4 --> T_7 --> T_10)\n (T_2 --> T_5 --> T_8)\n (T_3 --> T_6 --> T_9)\n\nRW edges (reader → writer):\n\n (T_4 --> T_3)\n (T_5 --> T_2)\n (T_6 --> T_3)\n (T_7 --> T_4)\n (T_8 --> T_5)\n (T_9 --> T_6)\n (T_10 --> T_7)\n\n### 3.2 Cycle Detection\n\nNo directed path returns to its starting transaction. Therefore, the conflict graph contains no simple cycles.\n\nResults:\n\n Total_Cycles = 0\n Largest_Cycle_Length = 0\n Is_Serializable = YES\n\n\n## 4. Final Answer (Copy-Paste Ready)\n\nTotal_WR_Conflicts: 0\nTotal_RW_Conflicts: 7\nTotal_WW_Conflicts: 7\nFinal_CCS: 132.48\nTotal_Cycles: 0\nLargest_Cycle_Length: 0\nIs_Serializable: YES"}
{"domain": "Computer Systems & Operating Systems", "prompt": "A processor allows instructions to overlap in execution by using a centralized scoreboarding mechanism rather than strict in-order completion. Execution resources are limited and non-pipelined: there is exactly one Integer execution unit (1-cycle latency), one floating-point unit capable of addition and subtraction (4-cycle latency), one floating-point multiplier (6-cycle latency), and one floating-point divider (9-cycle latency). No functional unit may accept a new instruction until the current one has fully completed execution.\n\nEach instruction progresses through four pipeline stages: dispatch, operand acquisition, execution, and result commitment. Dispatch is permitted only if the required functional unit is unused. Operand acquisition may not proceed until all required source operands are produced, thereby enforcing RAW correctness. Result commitment may be delayed if committing the value would violate a WAR dependency. Load instructions obtain their data using the Integer execution unit and follow identical hazard rules.\n\nAt the beginning of cycle 1, the register file contains the following values: \nR3 = 12, R5 = 24 \nF1 = 1.5, F3 = 3.0, F5 = 5.0, F7 = 7.0, F9 = 9.0, F11 = 11.0 \n\nStarting at cycle 1, the processor encounters the following instruction sequence in program order:\n\nI1: Load F3 from the memory location addressed by R3 \nI2: Multiply F5 using operands F3 and F7 \nI3: Add F7 using operands F5 and F9 \nI4: Divide F9 using operands F7 and F3 \nI5: Subtract to produce F11 using F9 and F5 \nI6: Load F1 from the memory location addressed by R5 \nI7: Multiply F3 using operands F1 and F11 \nI8: Add F5 using operands F3 and F7 \nI9: Divide F7 using operands F5 and F1 \nI10: Subtract to produce F9 using F7 and F3 \n\nFor each instruction, determine exactly which cycle it is dispatched, successfully reads its operands, completes execution and commits its result to the register file.\n\nUsing this execution timeline, compute the following quantities:\n\n1. The cycle at which the final instruction finishes committing its result \n2. The total of all dispatch cycle numbers \n3. The total of all result-commit cycle numbers \n4. The cumulative number of stall cycles caused by WAW conflicts \n5. The commit cycle of instruction I6 \n6. The earliest cycle at which the integer execution unit becomes permanently idle \n7. The maximum number of instructions simultaneously present in the system (issued but not yet committed) \n8. The instruction that experiences the longest continuous stall period\n9. The total number of cycles during which no instruction is able to dispatch \n10. The average execution-unit utilization across all functional units over the entire timeline ", "rubrics": [{"criterion": "Does the answer compute the cycle at which the final instruction finishes committing to be exactly cycle 66?", "weight": 10}, {"criterion": "Does the answer compute the total of all dispatch cycle numbers to be exactly 193?", "weight": 10}, {"criterion": "Does the answer compute the total of all result-commit cycle numbers to be exactly 339?", "weight": 10}, {"criterion": "Does the answer compute the cumulative number of stall cycles caused by WAW conflicts to be exactly 0?", "weight": 10}, {"criterion": "Does the answer state the commit cycle of instruction I6 to be cycle 23?", "weight": 10}, {"criterion": "Does the answer state the earliest cycle at which the integer execution unit becomes permanently idle to be cycle 24?", "weight": 10}, {"criterion": "Does the answer compute the maximum number of instructions simultaneously present in the system to be exactly 5?", "weight": 10}, {"criterion": "Does the answer state the instruction that experiences the longest continuous stall period to be exactly I4?", "weight": 10}, {"criterion": "Does the answer compute the total number of cycles during which no instruction is able to dispatch to be exactly 56?", "weight": 10}, {"criterion": "Does the answer compute the average execution-unit utilization across all functional units over the entire timeline to be approximately 18.2%?", "weight": 10}], "golden_answer": "Cycle 1: \n- I1: Load F3 from the memory location addressed by R3 \n - Integer unit is free\n - I1 dispatches\n- End state:\n - I1 dispatched\n - Integer unit reserved by I1, rest are free\n - F3 pending. Other registers unchanged.\n\n\nCycle 2: \n- I1: Load F3 from the memory location addressed by R3 \n - R3 ready\n - I1 successfully acquire operands\n- I2: Multiply F5 using operands F3 and F7\n - Multiplier unit free\n - I2 dispatches\n- End state:\n - I1 successfully acquire operands, I2 dispatched\n - Integer unit reserved by I1, Multiplier unit reserved by I2, rest are free\n - F3(I1) and F5(I2) pending. Other registers unchanged.\n\n\nCycle 3:\n- I1: Load F3 from the memory location addressed by R3 \n - Begins execution\n - Will execute for 1 cycle \n - Completes execution by end of cycle 3\n- I2: Multiply F5 using operands F3 and F7\n - F7 is free but F3 is pending\n - Operand read stalls\n- I3: Add F7 using operands F5 and F9 \n - Adder unit free\n - I3 dispatches\n- End state:\n - I1 executes for complete cycle, I2 stalled in Operand Read (RAW on F3), I3 dispatched\n - Integer unit reserved by I1, Multiplier unit reserved by I2, Adder unit reserved by I3, Divider free\n - F3(I1), F5(I2) and F7(I3) pending. Other registers unchanged.\n\n\nCycle 4:\n- I1: Load F3 from the memory location addressed by R3 \n - Commits F3\n - Leaves the system\n- I2: Multiply F5 using operands F3 and F7\n - F7 is free but F3 is pending\n - Operand read stalls\n- I3: Add F7 using operands F5 and F9 \n - F9 available but F5 is pending\n - Operand read stalls\n- I4: Divide F9 using operands F7 and F3 \n - Divider unit free\n - I4 dispatches\n- End state:\n - I1 commits F3 and leaves, I2 stalled in Operand Read (RAW on F3), I3 stalled in Operand Read (RAW on F5), I4 dispatched\n - Integer unit free, Multiplier unit reserved by I2, Adder unit reserved by I3, Divider unit reserved by I4\n - F5(I2), F7(I3) and F9(I4) pending. F3 ready. Other registers unchanged.\n\n\nCycle 5:\n- I2: Multiply F5 using operands F3 and F7\n - F3 and F7 both available (F7 is pending by later instruction)\n - Successfully acquire operands\n- I3: Add F7 using operands F5 and F9 \n - F9 available but F5 is pending\n - Operand read stalls\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I2 successfully acquire operands, I3 stalled in Operand Read (RAW on F5), I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit reserved by I2, Adder unit reserved by I3, Divider unit reserved by I4\n - F5(I2), F7(I3) and F9(I4) pending. F3 ready. Other registers unchanged.\n\n\nCycle 6:\n- I2: Multiply F5 using operands F3 and F7\n - Begins execution \n - Will execute for 6 cycles\n - Will complete execution by cycle 11\n- I3: Add F7 using operands F5 and F9 \n - F9 available but F5 is pending\n - Operand read stalls\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I2 starts execution, I3 stalled in Operand Read (RAW on F5), I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit reserved by I2, Adder unit reserved by I3, Divider unit reserved by I4\n - F5(I2), F7(I3) and F9(I4) pending. F3 ready. Other registers unchanged.\n\n\nCycle 7-11:\n- I2: Multiply F5 using operands F3 and F7\n - Executing (Finishes by the end of cycle 11)\n- I3: Add F7 using operands F5 and F9 \n - F9 available but F5 is pending\n - Operand read stalls\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I2 executing, I3 stalled in Operand Read (RAW on F5), I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit reserved by I2, Adder unit reserved by I3, Divider unit reserved by I4\n - F5(I2), F7(I3) and F9(I4) pending. F3 ready. Other registers unchanged.\n\n\nCycle 12:\n- I2: Multiply F5 using operands F3 and F7\n - Commits F5\n- I3: Add F7 using operands F5 and F9 \n - F9 available but F5 is pending\n - Operand read stalls\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I2 commits F5 and leaves, I3 stalled in Operand Read (RAW on F5), I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder unit reserved by I3, Divider unit reserved by I4\n - F7(I3) and F9(I4) pending. F3 and F5 ready. Other registers unchanged.\n\n\nCycle 13:\n- I3: Add F7 using operands F5 and F9 \n - F5 and F9 is available\n - Successfully read operands\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I3 successfully read operands, I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder unit reserved by I3, Divider unit reserved by I4\n - F7(I3) and F9(I4) pending. F3 and F5 ready. Other registers unchanged.\n\n\nCycle 14-17:\n- I3: Add F7 using operands F5 and F9 \n - Starts execution\n - Will execute for 4 cycles\n - Will complete execution by the end of cycle 17\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I3 executing, I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder unit reserved by I3, Divider unit reserved by I4\n - F7(I3) and F9(I4) pending. F3 and F5 ready. Other registers unchanged.\n\n\nCycle 18:\n- I3: Add F7 using operands F5 and F9 \n - Commits F7\n- I4: Divide F9 using operands F7 and F3 \n - F3 is available but F7 is pending by I3\n - Operand read stalls\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder not available\n- End state:\n - I3 commits F7 and leaves, I4 stalled in Operand Read (RAW on F7), I5 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder unit free, Divider unit reserved by I4\n - F9(I4) pending. F3, F5 and F7 ready. Other registers unchanged.\n\n\nCycle 19:\n- I4: Divide F9 using operands F7 and F3 \n - F3 and F7 both available\n - Successfully acquire operands\n- I5: Subtract to produce F11 using F9 and F5 \n - Adder available\n - Dispatches I5\n- End state:\n - I4 successfully acquire operands, I5 dispatched\n - Integer unit free, Multiplier unit free, Adder reserved by I5, Divider unit reserved by I4\n - F9(I4), F11(I5) pending. F3, F5 and F7 ready. Other registers unchanged.\n\n\nCycle 20:\n- I4: Divide F9 using operands F7 and F3 \n - Starts execution\n - Will execute for 9 cycles\n - Will complete execution by 28 \n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I6: Load F1 from the memory location addressed by R5\n - Integer unit available\n - Dispatches I6\n- End state:\n - I4 starts execution, I5 stalled in Operand Read (RAW on F9), I6 dispatched\n - Integer reserved by I6, Multiplier unit free, Adder reserved by I5, Divider unit reserved by I4\n - F1(I6), F9(I4), F11(I5) pending. F3, F5 and F7 ready. Other registers unchanged.\n\n\nCycle 21:\n- I4: Divide F9 using operands F7 and F3 \n - Executing\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I6: Load F1 from the memory location addressed by R5\n - R5 available \n - Successfully acquire operands\n- I7: Multiply F3 using operands F1 and F11 \n - Multiplier unit free\n - I7 dispatches\n- End state:\n - I4 executing, I5 stalled in Operand Read (RAW on F9), I6 successfully acquire operands, I7 dispatched\n - Integer reserved by I6, Multiplier reserved by I7, Adder reserved by I5, Divider unit reserved by I4\n - F1(I6), F3(I7), F9(I4), F11(I5) pending. F5 and F7 ready. Other registers unchanged.\n\n\nCycle 22:\n- I4: Divide F9 using operands F7 and F3 \n - Executing\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I6: Load F1 from the memory location addressed by R5\n - Starts execution \n - completes execution by the end of cycle\n- I7: Multiply F3 using operands F1 and F11 \n - F1 and F11 both are not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I4 executing, I5 stalled in Operand Read (RAW on F9), I6 executing, I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer reserved by I6, Multiplier reserved by I7, Adder reserved by I5, Divider unit reserved by I4\n - F1(I6), F3(I7), F9(I4), F11(I5) pending. F5 and F7 ready. Other registers unchanged.\n\n\nCycle 23:\n- I4: Divide F9 using operands F7 and F3 \n - Executing\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I6: Load F1 from the memory location addressed by R5\n - Commits F1\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I4 executing, I5 stalled in Operand Read (RAW on F9), I6 commit F1 and leaves, I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I5, Divider unit reserved by I4\n - F3(I7), F9(I4), F11(I5) pending. F1, F5 and F7 ready. Other registers unchanged.\n\n\nCycle 24-28:\n- I4: Divide F9 using operands F7 and F3 \n - Executing\n - Completes execution in cycle 28\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I4 executing, I5 stalled in Operand Read (RAW on F9), I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I5, Divider unit reserved by I4\n - F3(I7), F9(I4), F11(I5) pending. F1, F5 and F7 ready. Other registers unchanged.\n\n\nCycle 29:\n- I4: Divide F9 using operands F7 and F3 \n - Commits F9\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 is available but F9 is pending \n - Operand read stalls\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I4 commits F9 and leaves, I5 stalled in Operand Read (RAW on F9), I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I5, Divider unit free\n - F3(I7), F11(I5) pending. F1, F5, F7 and F9 ready. Other registers unchanged.\n\n\nCycle 30:\n- I5: Subtract to produce F11 using F9 and F5 \n - F5 and F9 both are available\n - Successfully acquire operands\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I5 successfully acquire operands, I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I5, Divider unit free\n - F3(I7), F11(I5) pending. F1, F5, F7 and F9 ready. Other registers unchanged.\n\n\nCycle 31-34:\n- I5: Subtract to produce F11 using F9 and F5 \n - Execution starts\n - Will be executing for 4 cycles\n - Will be completing execution by the end of cycle 34\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I5 starts execution, I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I5, Divider unit free\n - F3(I7), F11(I5) pending. F1, F5, F7 and F9 ready. Other registers unchanged.\n\n\n\nCycle 35:\n- I5: Subtract to produce F11 using F9 and F5 \n - Commit F11\n- I7: Multiply F3 using operands F1 and F11 \n - F1 is available but F11 is not available.\n - Operand read stalls\n- I8: Add F5 using operands F3 and F7 \n - Adder not available\n - Cannot dispatch\n- End state:\n - I5 commit F11 and leaves, I7 stalled in Operand Read (RAW on F1 and F11), I8 not dispatched\n - Integer unit free, Multiplier reserved by I7, Adder unit free, Divider unit free\n - F3(I7) pending. F1, F5, F7, F9 and F11 ready. Other registers unchanged.\n\n\nCycle 36:\n- I7: Multiply F3 using operands F1 and F11 \n - F1 and F11 both are available.\n - Successfully acquire operands\n- I8: Add F5 using operands F3 and F7 \n - Adder is available\n - I8 dispatches\n- End state:\n - I7 successfully acquire operands, I8 dispatched\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I8, Divider unit free\n - F3(I7), F5(I8) pending. F1, F7 and F9 ready. Other registers unchanged.\n\n\nCycle 37:\n- I7: Multiply F3 using operands F1 and F11 \n - Starts execution\n - Will be executing for 6 cycles\n - Will complete execution by cycle 42\n- I8: Add F5 using operands F3 and F7 \n - F7 is available but F3 is pending\n - Operand read stalls\n- I9: Divide F7 using operands F5 and F1 \n - Divider unit free\n - I9 dispatches\n- End state:\n - I7 starts execution, I8 stalled in Operand Read (RAW on F3), I9 dispatches\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I8, Divider reserved by I9\n - F3(I7), F5(I8), F7(I9) pending. F1 and F9 ready. Other registers unchanged.\n\n\n\nCycle 38:\n- I7: Multiply F3 using operands F1 and F11 \n - Executing\n- I8: Add F5 using operands F3 and F7 \n - F7 is available but F3 is pending\n - Operand read stalls\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I7 executing, I8 stalled in Operand Read (RAW on F3), I9 stalled in Operand Read (RAW on F5), I0 cannot dispatch\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I8, Divider reserved by I9\n - F3(I7), F5(I8), F7(I9) pending. F1 and F9 ready. Other registers unchanged.\n\n\nCycle 39-42:\n- I7: Multiply F3 using operands F1 and F11 \n - Executing\n - Completes execution by the end of cycle 42\n- I8: Add F5 using operands F3 and F7 \n - F7 is available but F3 is pending\n - Operand read stalls\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I7 completes execution by the end of cycle 42, I8 stalled in Operand Read (RAW on F3), I9 stalled in Operand Read (RAW on F5), I0 cannot dispatch\n - Integer unit free, Multiplier reserved by I7, Adder reserved by I8, Divider reserved by I9\n - F3(I7), F5(I8), F7(I9) pending. F1 and F9 ready. Other registers unchanged.\n\n\nCycle 43:\n- I7: Multiply F3 using operands F1 and F11 \n - Commits F3\n- I8: Add F5 using operands F3 and F7 \n - F7 is available but F3 is pending\n - Operand read stalls\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I7 commits F3 and leaves, I8 stalled in Operand Read (RAW on F3), I9 stalled in Operand Read (RAW on F5), I0 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder reserved by I8, Divider reserved by I9\n - F5(I8), F7(I9) pending. F1, F3 and F9 ready. Other registers unchanged.\n\n\nCycle 44:\n- I8: Add F5 using operands F3 and F7 \n - F3 and F7 are available\n - Successfully acquire operands\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I8 successfully acquire operands, I9 stalled in Operand Read (RAW on F5), I10 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder reserved by I8, Divider reserved by I9\n - F5(I8), F7(I9) pending. F1, F3 and F9 ready. Other registers unchanged.\n\n\nCycle 45-48:\n- I8: Add F5 using operands F3 and F7 \n - Starts execution\n - Will execute for 4 cycles\n - Will complete execution by the end of cycle 48\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I8 executing, I9 stalled in Operand Read (RAW on F5), I10 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder reserved by I8, Divider reserved by I9\n - F5(I8), F7(I9) pending. F1, F3 and F9 ready. Other registers unchanged.\n\n\nCycle 49:\n- I8: Add F5 using operands F3 and F7 \n - Commits F5\n- I9: Divide F7 using operands F5 and F1 \n - F1 is available but F5 is pending\n - Operand read stalls\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder not available\n - Cannot dispatch I10\n- End state:\n - I8 commits F5 and leaves, I9 stalled in Operand Read (RAW on F5), I10 cannot dispatch\n - Integer unit free, Multiplier unit free, Adder unit free, Divider reserved by I9\n - F7(I9) pending. F1, F3, F5 and F9 ready. Other registers unchanged.\n\n\nCycle 50:\n- I9: Divide F7 using operands F5 and F1 \n - F1 and F5 both are available\n - Successfully acquire operands\n- I10: Subtract to produce F9 using F7 and F3 \n - Adder is available\n - I10 dispatches\n- End state:\n - I9 successfully acquire operands, I0 dispatched\n - Integer unit free, Multiplier unit free, Adder unit reserved by I10, Divider reserved by I9\n - F7(I9), F9(I10) pending. F1, F3, F5 ready. Other registers unchanged.\n\n\nCycle 51-59:\n- I9: Divide F7 using operands F5 and F1 \n - Starts execution \n - Will execute for 9 cycles\n - Will complete execution by the end of cycle 59\n- I10: Subtract to produce F9 using F7 and F3 \n - F3 is available but F7 is pending\n - Operand read stalls\n- End state:\n - I9 starts execution, I0 stalled in Operand Read (RAW on F7)\n - Integer unit free, Multiplier unit free, Adder unit reserved by I10, Divider reserved by I9\n - F7(I9), F9(I10) pending. F1, F3, F5 ready. Other registers unchanged.\n\n\nCycle 60:\n- I9: Divide F7 using operands F5 and F1 \n - Commits F7\n- I10: Subtract to produce F9 using F7 and F3 \n - F3 is available but F7 is pending\n - Operand read stalls\n- End state:\n - I9 commit F7 and leaves, I0 stalled in Operand Read (RAW on F7)\n - Integer unit free, Multiplier unit free, Adder unit reserved by I10, Divider unit free\n - F9(I10) pending. F1, F3, F5, F7 ready. Other registers unchanged.\n\n\nCycle 61:\n- I10: Subtract to produce F9 using F7 and F3 \n - F3 and F7 both are available\n - Successfully acquire operands\n- End state:\n - I0 successfully acquire operands\n - Integer unit free, Multiplier unit free, Adder unit reserved by I10, Divider unit free\n - F9(I10) pending. F1, F3, F5, F7 ready. Other registers unchanged.\n\n\nCycle 62-65:\n- I10: Subtract to produce F9 using F7 and F3 \n - Starts execution\n - Will be executing for 4 cycles\n - Will complete execution by cycle 65 \n- End state:\n - I0 executing\n - Integer unit free, Multiplier unit free, Adder unit reserved by I10, Divider unit free\n - F9(I10) pending. F1, F3, F5, F7 ready. Other registers unchanged.\n\n\nCycle 66:\n- I10: Subtract to produce F9 using F7 and F3 \n - Commit F9\n- End state:\n - I0 commits F9 and leavs\n - Integer unit free, Multiplier unit free, Adder unit free, Divider unit free\n - F1, F3, F5, F7 and F9 ready. Other registers unchanged.\n\n\n\nFinal answers \n1. The cycle at which the final instruction finishes committing its result \nCycle 66\n\n2. The total of all dispatch cycle numbers \n1 + 2 + 3 + 4 + 19 + 20 + 21 + 36 + 37 + 50 = 193\n\n3. The total of all result-commit cycle numbers \n339\n\n4. The cumulative number of stall cycles caused by WAW conflicts \n0\n\n5. The commit cycle of instruction I6 \n23\n\n6. The earliest cycle at which the integer execution unit becomes permanently idle \n24\n\n7. The maximum number of instructions simultaneously present in the system (issued but not yet committed) \n5\n\n8. The instruction that experiences the longest continuous stall period\nI4\n\n9. The total number of cycles during which no instruction is able to dispatch \n56\n\n10. The average execution-unit utilization across all functional units over the entire timeline \n| Unit | Busy cycles |\n| ----------- | ----------- |\n| Integer | 2 |\n| FP Add/Sub | 16 |\n| FP Multiply | 12 |\n| FP Divide | 18 |\n\nTotal possible = 4 × 66 = 264\nUtilization = 48/264 = 18.2%\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given multiple test cases. In each test case, you are given an array `p` of length `n` describing a permutation of `{1,2,…,n}` with missing elements: some `p[i] = -1`, and all non-`-1` values in `p` are **distinct**.\n\nA permutation `b` of length `n` is called a **riffle shuffle** of the sorted permutation `[1,2,…,n]` if there exists an integer `k` with `1 ≤ k < n` such that:\n- the sequence `1,2,…,k` appears as a subsequence of `b`, and\n- the sequence `k+1,k+2,…,n` appears as a subsequence of `b`.\n\nYour task: for each test case, count the number of distinct ways to replace every `-1` in `p` with the missing integers (so that the result is a full permutation of `1..n`) such that the resulting permutation is a riffle shuffle of `[1..n]`.\n\nOutput the answer modulo `998244353`.\n\n### Input format\n- First line: integer `t` (number of test cases).\nFor each test case:\n- Line 1: integer `n`.\n- Line 2: `n` integers `p[1..n]` (each is `-1` or in `[1..n]`), with all non-`-1` distinct.\n\n### Output format\nFor each test case, output one integer: the number of valid completions modulo `998244353`.\n", "rubrics": [{"criterion": "For a known value v at position i with v<=k, the answer states the exact prefix constraint B[i]=v (i.e., exactly v BLUE positions among indices 1..i).", "weight": 10}, {"criterion": "For a known value v at position i with v>k, the answer states the exact prefix constraint B[i]=i-(v-k).", "weight": 10}, {"criterion": "The answer explicitly states that if two constraints assign different required values to the same prefix length j, then that split k contributes 0 (is discarded).", "weight": 10}, {"criterion": "The answer computes the number of valid colorings in a feasible block as exactly the binomial coefficient C(len, need).", "weight": 10}, {"criterion": "The answer includes an explicit correction for the sorted completion case (when compatible with the partial p) to avoid overcounting across k (e.g., subtracting n-2 modulo 998244353).", "weight": 10}, {"criterion": "The answer reformulates the problem for a fixed split k by coloring values v<=k as BLUE and values v>k as RED.", "weight": 10}, {"criterion": "For a known value v at position i with v<=k, the answer states the exact constraint B[i-1]=v-1 (forcing position i itself to be BLUE).", "weight": 10}, {"criterion": "The answer states the feasibility condition between consecutive constrained prefixes: for a block with len=jb-ja and need=Bb-Ba, it must hold that 0<=need<=len.", "weight": 10}, {"criterion": "The answer includes an aggregation step that sums count(k) over all k from 1 to n-1 to form the total.", "weight": 10}, {"criterion": "For a known value v at position i with v>k, the answer states the exact constraint B[i-1]=B[i] (forcing position i itself to be RED).", "weight": 10}], "golden_answer": "Let MOD = 998244353. Precompute factorials `fact[i]` and inverse factorials `invfact[i]` up to the maximum `n` across all test cases, so `C(n,r) = fact[n]*invfact[r]*invfact[n-r] mod MOD`.\n\nKey uniqueness fact (split-point identification):\n- For any riffle shuffle permutation `q` that is **not** fully sorted, the split value `k` is uniquely determined as the smallest integer such that `k` appears after `k+1` in `q`.\n- The only riffle shuffle permutation where no such `k` exists is the sorted permutation `[1,2,…,n]`, which is valid for every `k` and therefore must be handled to avoid overcounting.\n\nFix a split value `k` (1 ≤ k < n). Color values `1..k` as BLUE and `k+1..n` as RED. A completion is valid for this `k` iff the BLUE values appear in increasing order and the RED values appear in increasing order; once the BLUE/RED pattern of positions is fixed, the final permutation is uniquely determined by scanning left-to-right and assigning the next unused BLUE number or RED number.\n\nPrefix-count reformulation (explicit constraints):\nDefine `B[j]` = number of BLUE positions among the first `j` positions (prefix length `j`), for `j = 0..n`.\nThen necessarily:\n- `B[0] = 0`\n- `B[n] = k`\n- For every position `i` with known value `v = p[i] != -1`:\n\n 1) If `v ≤ k` (BLUE value), then:\n - `B[i] = v` (exactly `v` blues in positions `1..i`)\n - `B[i-1] = v-1` (position `i` itself must be BLUE)\n\n 2) If `v > k` (RED value), then the number of reds in `1..i` must be `v-k`, so:\n - `B[i] = i - (v-k)` (since blues = i − reds)\n - `B[i-1] = B[i]` (position `i` itself must be RED)\n\nIf any prefix length `j` gets two different required values, this `k` is impossible.\n\nCounting for a fixed k using binomials:\nLet `req[j]` store the required value of `B[j]` (or “unset”). Initialize:\n- `req[0]=0`, `req[n]=k`, and add the above constraints from every known `p[i]`.\n\nCollect all prefix indices `j` where `req[j]` is set, sort them increasingly: `j0 < j1 < ... < jm`.\nFor each consecutive pair `(ja, Ba=req[ja])` and `(jb, Bb=req[jb])`:\n- `len = jb - ja` (number of positions in this block)\n- `need = Bb - Ba` (number of BLUE positions in that block)\nFeasibility condition (must hold):\n- `0 ≤ need ≤ len`\nIf not, this `k` is impossible.\nOtherwise, the number of ways to choose which positions in this block are BLUE is exactly:\n- `C(len, need)`\nMultiply these contributions over all blocks to get `count(k)`.\n\nSorted permutation special case:\nCheck whether the fully sorted permutation `[1..n]` is compatible with the partial input: i.e., for every `i`, if `p[i] != -1` then `p[i] == i`. If compatible, there is exactly one “sorted completion”; call this `sorted_ok = 1`, else `0`.\n\nFinal aggregation:\nCompute `S = sum_{k=1..n-1} count(k) mod MOD`.\nIf `sorted_ok = 1`, the sorted completion was counted once for every `k` (i.e., `n-1` times), but must be counted once total, so subtract `(n-2)`:\n- `answer = (S - (n-2)) mod MOD`\nElse:\n- `answer = S`\nOutput `answer` modulo MOD (normalized to [0, MOD)).\n\n(Implementation note: `C(len, need)` is computed in O(1) using factorials and inverse factorials.)\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given an integer sequence `a = [a1, a2, …, an]`, where each value represents the height of a structure placed in a line.\n\n### Visibility rule (record highs)\nDefine two collections derived from a sequence `x`:\n\n- **Left-visible heights** `L(x)`: scan `x` from left to right and write down a height whenever it is **strictly greater** than every height seen earlier in the scan.\n- **Right-visible heights** `R(x)`: scan `x` from right to left and write down a height whenever it is **strictly greater** than every height seen earlier in that right-to-left scan (equivalently: strictly greater than all elements to its right).\n\nThese collections are treated as **sets of height values** (duplicates are irrelevant).\n\n#### Example\nFor `x = [2, 4, 4, 1, 5, 3]`:\n- `L(x) = {2, 4, 5}`\n- `R(x) = {3, 5}`\n\n### What you must count\nA **subsequence** `a'` is obtained by choosing a subset of indices `1 ≤ i1 < i2 < … < ik ≤ n` and taking:\n`a' = [ai1, ai2, …, aik]`.\n\nCount how many subsequences `a'` satisfy **both** of the following:\n- `L(a') = L(a)`\n- `R(a') = R(a)`\n\nTwo subsequences are considered different if they are formed from different index sets, even if their values are identical.\n\nBecause the answer can be large, output it modulo:\n\n`998244353`.\n\n---\n\n## Input\nThe first line contains an integer `t` — the number of test cases.\n\nFor each test case:\n- The first line contains an integer `n` (`1 ≤ n ≤ 5000`)\n- The second line contains `n` integers `a1, a2, …, an` (`1 ≤ ai ≤ 10^9`)\n\nAdditional constraint:\n- The sum of `n` over all test cases does not exceed `5000`.\n\n---\n\n## Output\nFor each test case, print a single integer: the number of subsequences `a'` such that \n`L(a') = L(a)` and `R(a') = R(a)`, modulo `998244353`.\n", "rubrics": [{"criterion": "Does the answer define L(a) as the record-high values when scanning left to right using a strict 'greater than all previous' rule?", "weight": 1}, {"criterion": "Does the answer state that when processing a non-maximum element x with x <= the last visible value of the current prefix, the DP value for that prefix is multiplied by 2 (take/skip)?", "weight": 1}, {"criterion": "Does the answer specify dpL[i] for positions with a[i] = m as the number of subsequences that match L(a) excluding its last element (expressed as dpL[i] = c[k-1] or equivalent)?", "weight": 1}, {"criterion": "Does the answer give the final sum formula over i <= j with a[i] = a[j] = m as dpL[i] * dpR[j] * 2^(j-i-1) modulo 998244353?", "weight": 1}, {"criterion": "Does the answer state that the final result is computed modulo 998244353?", "weight": 1}, {"criterion": "Does the answer state that when processing a non-maximum element x that equals the next required visible value L[p], the transition adds c[p] into c[p+1]?", "weight": 1}, {"criterion": "Does the answer state that the computed right-DP results are converted back to the original indexing?", "weight": 1}, {"criterion": "Does the answer define m as max(a) (the maximum element of the sequence)?", "weight": 1}, {"criterion": "Does the answer state the DP initialization c[0] = 1 (with other c values initially 0)?", "weight": 1}, {"criterion": "Does the answer define R(a) as the record-high values when scanning right to left using a strict 'greater than all after' rule?", "weight": 1}], "golden_answer": "### Overview\nWe need to count subsequences `a'` whose **left-visible set** and **right-visible set** match those of the original sequence `a`.\n\nLet:\n- `L(a)` be the (strictly increasing) sequence of record highs seen from the left.\n- `R(a)` be the (strictly increasing, in right-to-left scan order) record highs seen from the right.\n- `m = max(a)`. The value `m` must appear in any valid subsequence and is visible from both sides.\n\nThe main idea is to **fix the first and last occurrence of `m` inside the subsequence**, then multiply independent counts for:\n1) building the required left view up to the first `m`,\n2) building the required right view from the last `m`,\n3) freely choosing elements strictly between those two maxima.\n\nAll arithmetic is done modulo `998244353`.\n\n---\n\n### Step 1: Compute `L(a)` and `R(a)`\nScan:\n- From left to right, append `a[i]` to `L` if it is strictly greater than all previous.\n- From right to left, append `a[i]` to `R` if it is strictly greater than all to its right.\n\nLet `L` have length `k`. Note that `L[k-1] = m`.\n\n---\n\n### Step 2: Count valid prefixes ending at each maximum (`dpL`)\nFor each position `i` with `a[i] = m`, define:\n\n- `dpL[i]` = number of subsequences formed using indices `≤ i`\n such that their left-visible sequence equals `L` **without its last element** (i.e., the first `k-1` record highs),\n and additionally **no `m` is chosen before position `i`**.\n\nThen, if we append `a[i]=m` as the first maximum, the left view becomes exactly `L(a)`.\n\n#### How to compute `dpL`\nMaintain an array `c[0..k-1]` where:\n- `c[p]` = number of subsequences whose left-visible sequence equals the first `p` elements of `L`\n (so `p` ranges from `0` to `k-1`, since we do *not* want to place `m` yet).\n\nInitialization:\n- `c[0] = 1`, all other `c[p] = 0`.\n\nProcess elements from left to right. For each `x = a[i]`:\n- If `x == m`:\n - set `dpL[i] = c[k-1]` (these are exactly the subsequences that already match the first `k-1` visible heights),\n - and **do not** allow selecting `x` into `c` (we skip it in the DP so that future maxima can still be “first maximum” candidates).\n\n- Otherwise, update `c` to reflect the choice “take `x`” or “skip `x`”, under the constraint that the left-visible sequence must remain a prefix of `L`:\n\nFor each prefix length `p`:\n- Let `last = (p == 0 ? -∞ : L[p-1])`.\n- If `x <= last`, then taking or skipping `x` does not change the visible record highs:\n - `c[p] := 2 * c[p]`.\n- Else (`x > last`), the only way to take `x` without breaking the required left-visible sequence is if it equals the *next* needed visible height:\n - if `p < k-1` and `x == L[p]`, then we can extend:\n - `c[p+1] += c[p]` (take `x`),\n - and also keep `c[p]` as-is (skip `x`).\n - if `x > last` but `x != L[p]`, we cannot take `x` (only skipping is allowed), so `c[p]` stays unchanged.\n\nThis DP runs in `O(n * k)`, and `k ≤ n`, so `O(n^2)`.\n\n---\n\n### Step 3: Count valid suffixes starting at each maximum (`dpR`)\nSimilarly define for each position `j` with `a[j] = m`:\n\n- `dpR[j]` = number of subsequences using indices `≥ j`\n such that their right-visible sequence equals `R(a)` without its last element,\n and **no `m` is chosen after position `j`**.\n\nCompute `dpR` by running the same DP logic on the reversed sequence (and using the record highs of `R(a)` in the appropriate order), then map results back to original indices.\n\n---\n\n### Step 4: Combine by fixing first/last maximum\nFix positions `i ≤ j` with `a[i] = a[j] = m`, where:\n- `i` is the first chosen maximum in the subsequence,\n- `j` is the last chosen maximum in the subsequence.\n\nElements strictly between `i` and `j` can be chosen arbitrarily: they are “sandwiched” between maxima and cannot affect visibility from either side.\n\nLet `x = j - i - 1` be the number of elements between them. Then the number of choices is `2^x`.\n\nContribution of pair `(i, j)`:\n- `dpL[i] * dpR[j] * 2^(j-i-1)`.\n\nSo the final answer is:\n\\[\n\\text{ans} = \\sum_{\\substack{i \\le j \\\\ a[i]=a[j]=m}} dpL[i] \\cdot dpR[j] \\cdot 2^{(j-i-1)} \\pmod{998244353}.\n\\]\n\nPrecompute powers of two up to `n` modulo `998244353`.\n\n---\n\n### Complexity\n- Computing `L(a)` and `R(a)`: `O(n)`\n- Computing `dpL` and `dpR`: `O(n^2)`\n- Summing over maximum pairs: `O(n^2)` in the worst case\n\nTotal per test file fits the constraints because `∑n ≤ 5000`.\n\n---\n"}
{"domain": "Computer Systems & Operating Systems", "prompt": "# Operating Systems / Storage (RAID): Deterministic Layout, Parity Update, Rebuild, and Reliability\n\n## Global constants (used everywhere)\n\n- Disks are named: `D0, D1, D2, D3, D4` (5 disks total).\n- Sector size is irrelevant except for parity; for this task **each sector stores exactly 1 byte**.\n- A stripe unit (chunk) is **4 sectors**.\n- All XOR parity is byte-wise XOR (8-bit).\n\n### Common stripe indexing\nLet logical address be in **sectors**:\n- RAID5 has **4 data disks per stripe** ⇒ logical stripe width:\n \\[\n W_{5}=4\\cdot 4=16 \\text{ logical sectors per stripe}\n \\]\n- Stripe number:\n \\[\n s = \\left\\lfloor \\frac{\\text{LBA}}{16}\\right\\rfloor\n \\]\n- Position within stripe:\n \\[\n p = \\text{LBA}\\bmod 16\n \\]\n- Data-chunk index within stripe:\n \\[\n j = \\left\\lfloor \\frac{p}{4}\\right\\rfloor \\in \\{0,1,2,3\\}\n \\]\n- Offset within chunk:\n \\[\n o = p \\bmod 4 \\in \\{0,1,2,3\\}\n \\]\n- Physical sector number on a disk for stripe `s` at offset `o` is:\n \\[\n \\text{physSector} = 4s + o\n \\]\n\n---\n\n## Part A — RAID 5 (distributed parity, **layout is fixed and must be used**)\n\n### RAID5 layout rule (left-asymmetric, deterministic)\nFor stripe number `s`:\n- Parity disk:\n \\[\n pDisk = s \\bmod 5\n \\]\n- The 4 data chunks `j=0..3` are placed on disks:\n \\[\n dDisk(j) = (pDisk + 1 + j) \\bmod 5\n \\]\n- For any stripe `s` and offset `o`, parity byte stored on `pDisk` at sector `4s+o` is:\n \\[\n P[s,o] = D[s,0,o]\\oplus D[s,1,o]\\oplus D[s,2,o]\\oplus D[s,3,o]\n \\]\n where `D[s,j,o]` is the data byte for chunk `j` offset `o`.\n\n### RAID5 read requests (must map to physical disk sector reads)\nCompute the minimal set of physical read operations for each request, using this rule:\n\n**Read-I/O grouping rule:** within the same disk, merge any reads that touch **contiguous sector ranges** into one `(disk,start,len)` tuple.\n\nOutput tuples must be sorted by disk number ascending and, within a disk, by `start` ascending.\n\n#### RAID5 Read Request R1\nRead `len=22` logical sectors starting at `LBA=14` (i.e., LBAs 14..35).\n\n#### RAID5 Read Request R2\nRead `len=18` logical sectors starting at `LBA=7` (i.e., LBAs 7..24).\n\n---\n\n## Part B — RAID5 write W (parity update) and I/O counts\n\n### Deterministic write W\nWrite `len=11` logical sectors starting at `LBA=23` (LBAs 23..33).\nThe new sector bytes (in order of increasing LBA) are:\n\n`A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA` (hex bytes, uppercase, no `0x`).\n\n### RAID5 initial on-disk bytes (only stripes used by W are provided)\n\nStripe `s=1` (so sectors `4..7` on each disk for offsets `o=0..3`):\n- Parity disk is `D1`. Data disks are `D2 (j=0), D3 (j=1), D4 (j=2), D0 (j=3)`.\n\nGiven **data bytes** (offsets `o=0,1,2,3`):\n- `D2: 10 11 12 13`\n- `D3: 20 21 22 23`\n- `D4: 30 31 32 33`\n- `D0: 40 41 42 43`\n\nStripe `s=2` (sectors `8..11` on each disk):\n- Parity disk is `D2`. Data disks are `D3 (j=0), D4 (j=1), D0 (j=2), D1 (j=3)`.\n\nGiven **data bytes**:\n- `D3: 55 56 57 58`\n- `D4: 65 66 67 68`\n- `D0: 75 76 77 78`\n- `D1: 05 06 07 08`\n\n### RAID5 write-parity update rule (must follow exactly)\nWrite uses **read-modify-write** with these exact rules:\n\nFor each stripe `s` touched by the write:\n1. Read the **entire parity chunk** for that stripe: 4 contiguous sectors on `pDisk` → counts as **1 read I/O**.\n2. For each data disk that has any sectors overwritten in that stripe, read the overwritten sectors on that disk; within that disk, merge contiguous reads → counts as read I/O(s).\n3. Write the new data sectors (merged per disk into contiguous runs) → counts as write I/O(s).\n4. Write back the **entire parity chunk** for that stripe (4 contiguous sectors) → counts as **1 write I/O**.\n\n**Important:** Reads/writes on the same disk may be merged into a single I/O if they are contiguous *even if they belong to different stripes* (because physical sectors are contiguous). Use the same merge rule as in Part A.\n\n### What you must compute for RAID5 write W\n- `WRITE_W_IO_RAID5`: total read I/Os and total write I/Os for the entire write W.\n- `RAID5_PARITY_STRIPE1`: the 4 parity bytes on `D1` sectors `4..7` after W completes, as comma-separated hex bytes.\n- `RAID5_PARITY_STRIPE2`: the 4 parity bytes on `D2` sectors `8..11` after W completes.\n\n---\n\n## Part C — RAID 4 (dedicated parity) on the same 5 disks\n\nRAID4 uses:\n- Data disks: `D0..D3`\n- Dedicated parity disk: `D4`\n\nChunk size is still 4 sectors, and logical stripe width is also \\(16\\) sectors.\n\n### RAID4 layout rule (deterministic)\nFor stripe `s`:\n- Chunk `j` is stored on disk `Dj` for `j=0..3` (so `j=0→D0`, `j=1→D1`, etc.).\n- Parity is stored on `D4`, and for each offset `o`:\n \\[\n P4[s,o] = D0[s,o]\\oplus D1[s,o]\\oplus D2[s,o]\\oplus D3[s,o]\n \\]\n- Physical sector on any disk for stripe `s` offset `o` is `4s+o`.\n\n### RAID4 initial bytes (only stripes used by W are provided)\n\nStripe `s=1` (sectors `4..7`):\n- `D0: 01 02 03 04`\n- `D1: 05 06 07 08`\n- `D2: 09 0A 0B 0C`\n- `D3: 0D 0E 0F 10`\n\nStripe `s=2` (sectors `8..11`):\n- `D0: 21 22 23 24`\n- `D1: 25 26 27 28`\n- `D2: 29 2A 2B 2C`\n- `D3: 2D 2E 2F 30`\n\n(Parity on `D4` is implied by XOR; you may compute it.)\n\n### RAID4 write behavior for W\nApply the same **read-modify-write I/O rules** as RAID5, except:\n- parity disk is always `D4`.\n\n### What you must compute for RAID4 under the same W\n- `WRITE_W_IO_RAID4`: total read I/Os and total write I/Os.\n- `RAID4_PARITY`: after W completes, output:\n - stripe1 parity bytes on `D4` sectors `4..7`\n - stripe2 parity bytes on `D4` sectors `8..11`\n\n---\n\n## Part D — RAID5 rebuild check (coupled to your parity result)\nAfter RAID5 write W completes, assume **disk D2 fails** completely.\n\nCompute the reconstructed byte that should be stored at:\n- stripe `s=1`, chunk `j=0`, offset `o=1`\n\nOutput that reconstructed byte as **two hex digits**.\n\n---\n\n## Part E — Reliability (numeric, deterministic rounding)\n\nLet per-disk failure probability over the period be:\n\\[\np = 0.03\n\\]\nAssume independent disk failures.\n\nCompute data-loss probability (rounded to **exactly 10 digits after the decimal point**):\n\n1. `P_LOSS_RAID0_5DISKS_p0.03`: RAID0 on 5 disks (loss if **any** disk fails).\n2. `P_LOSS_RAID5_5DISKS_p0.03`: RAID5 on 5 disks (loss if **2 or more** disks fail).\n3. `P_LOSS_RAID1_2DISKS_p0.03`: RAID1 mirrored pair (2 disks; loss if **both** fail).\n\n---\n\n## Required Output Format\n\nProvide your reasoning, then output a final answer block containing **exactly 11 lines** in this exact order:\n\n1. `RAID5_READ_REQ1: ...`\n2. `RAID5_READ_REQ2: ...`\n3. `WRITE_W_IO_RAID5: reads=N writes=N`\n4. `WRITE_W_IO_RAID4: reads=N writes=N`\n5. `RAID5_PARITY_STRIPE1: D1[4..7]=..,..,..,..`\n6. `RAID5_PARITY_STRIPE2: D2[8..11]=..,..,..,..`\n7. `RAID4_PARITY: stripe1 D4[4..7]=..,..,..,.. | stripe2 D4[8..11]=..,..,..,..`\n8. `REBUILD_RAID5_D2_s1_j0_o1: ..`\n9. `P_LOSS_RAID0_5DISKS_p0.03: 0.xxxxxxxxxx`\n10. `P_LOSS_RAID5_5DISKS_p0.03: 0.xxxxxxxxxx`\n11. `P_LOSS_RAID1_2DISKS_p0.03: 0.xxxxxxxxxx`\n", "rubrics": [{"criterion": "Line 1 is exactly `RAID5_READ_REQ1: (D0,4,4) (D2,4,4) (D3,4,8) (D4,2,6)`.", "weight": 10}, {"criterion": "Line 2 is exactly `RAID5_READ_REQ2: (D2,3,5) (D3,0,8) (D4,0,5)`.", "weight": 10}, {"criterion": "Line 3 is exactly `WRITE_W_IO_RAID5: reads=5 writes=5`.", "weight": 10}, {"criterion": "Line 4 is exactly `WRITE_W_IO_RAID4: reads=5 writes=5`.", "weight": 10}, {"criterion": "Line 5 is exactly `RAID5_PARITY_STRIPE1: D1[4..7]=34,34,34,BF`.", "weight": 20}, {"criterion": "Line 6 is exactly `RAID5_PARITY_STRIPE2: D2[8..11]=BC,BC,40,40`.", "weight": 20}, {"criterion": "Line 7 is exactly `RAID4_PARITY: stripe1 D4[4..7]=00,00,00,A8 | stripe2 D4[8..11]=88,88,00,10`.", "weight": 20}, {"criterion": "Line 8 is exactly `REBUILD_RAID5_D2_s1_j0_o1: 11`.", "weight": 15}, {"criterion": "Line 9 is exactly `P_LOSS_RAID0_5DISKS_p0.03: 0.1412659743`.", "weight": 10}, {"criterion": "Line 10 is exactly `P_LOSS_RAID5_5DISKS_p0.03: 0.0084720528`.", "weight": 10}, {"criterion": "Line 11 is exactly `P_LOSS_RAID1_2DISKS_p0.03: 0.0009000000`.", "weight": 10}, {"criterion": "Does the final answer block contain exactly 11 lines in the specified order and format, regardless of any preceding reasoning?", "weight": 5}], "golden_answer": "### Request R1: read LBAs 14..35 (len=22)\n\n- Stripe 0 covers LBA 0..15. Need LBA 14..15.\n - Stripe 0: \\(pDisk=0\\). For \\(p=14,15\\Rightarrow j=3\\), disk is \\(dDisk(3)=(0+1+3)\\bmod5=4\\Rightarrow D4\\).\n - Offsets \\(o=2,3\\) ⇒ D4 sectors 2..3 ⇒ \\((D4,2,2)\\).\n\n- Stripe 1 covers LBA 16..31. Need entire stripe.\n - Stripe 1: \\(pDisk=1\\). Data disks:\n - \\(j=0\\to D2\\) sectors 4..7\n - \\(j=1\\to D3\\) sectors 4..7\n - \\(j=2\\to D4\\) sectors 4..7\n - \\(j=3\\to D0\\) sectors 4..7\n\n- Stripe 2 covers LBA 32..47. Need LBA 32..35.\n - Stripe 2: \\(pDisk=2\\). \\(p=0..3\\Rightarrow j=0\\to D3\\) sectors 8..11 ⇒ \\((D3,8,4)\\).\n\nMerge contiguous reads per disk:\n- D4: (2,2) and (4,4) merge ⇒ \\((D4,2,6)\\)\n- D3: (4,4) and (8,4) merge ⇒ \\((D3,4,8)\\)\n- D0: \\((D0,4,4)\\)\n- D2: \\((D2,4,4)\\)\n\n**RAID5_READ_REQ1:** `(D0,4,4) (D2,4,4) (D3,4,8) (D4,2,6)`\n\n### Request R2: read LBAs 7..24 (len=18)\n\n- Stripe 0 need LBA 7..15:\n - LBA 7: \\(j=1,o=3\\) on \\(D2\\) sector 3 ⇒ \\((D2,3,1)\\)\n - LBA 8..11: \\(j=2\\) on \\(D3\\) sectors 0..3 ⇒ \\((D3,0,4)\\)\n - LBA 12..15: \\(j=3\\) on \\(D4\\) sectors 0..3 ⇒ \\((D4,0,4)\\)\n\n- Stripe 1 need LBA 16..24 (p=0..8):\n - p=0..3: \\(j=0\\) on D2 sectors 4..7 ⇒ \\((D2,4,4)\\)\n - p=4..7: \\(j=1\\) on D3 sectors 4..7 ⇒ \\((D3,4,4)\\)\n - p=8: \\(j=2\\) on D4 sector 4 ⇒ \\((D4,4,1)\\)\n\nMerge per disk:\n- D2: sector 3 and 4..7 merge ⇒ \\((D2,3,5)\\)\n- D3: 0..3 and 4..7 merge ⇒ \\((D3,0,8)\\)\n- D4: 0..3 and 4 merge ⇒ \\((D4,0,5)\\)\n\n**RAID5_READ_REQ2:** `(D2,3,5) (D3,0,8) (D4,0,5)`\n\n---\n\n## Part B — RAID5 write W (LBA 23..33): parity + I/O counts\n\nWrite bytes (in LBA order): `A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA`.\n\nMapping:\n- Stripe 1 (LBA 16..31), \\(pDisk=1\\):\n - LBA 23 (p=7): \\(j=1,o=3\\) ⇒ D3 sector 7 gets A0\n - LBA 24..27 (p=8..11): \\(j=2\\) ⇒ D4 sectors 4..7 get A1..A4\n - LBA 28..31 (p=12..15): \\(j=3\\) ⇒ D0 sectors 4..7 get A5..A8\n- Stripe 2 (LBA 32..47), \\(pDisk=2\\):\n - LBA 32..33 (p=0..1): \\(j=0\\) ⇒ D3 sectors 8..9 get A9,AA\n\nOverwritten per disk:\n- D3 sectors 7..9 (contiguous) ⇒ one run\n- D4 sectors 4..7\n- D0 sectors 4..7\n\n### RAID5 I/O counts (read-modify-write)\nParity reads: stripe1 on D1 (4..7) + stripe2 on D2 (8..11) ⇒ 2 read I/Os. \nData reads (merged even across stripes): D3 (7..9) + D4 (4..7) + D0 (4..7) ⇒ 3 read I/Os. \nTotal reads = 5.\n\nData writes: D3 + D4 + D0 ⇒ 3 write I/Os. \nParity writes: D1 (4..7) + D2 (8..11) ⇒ 2 write I/Os. \nTotal writes = 5.\n\nSo: `WRITE_W_IO_RAID5: reads=5 writes=5`.\n\n### RAID5 parity after W\n\nStripe 1 parity (on D1[4..7]):\n- Data after write:\n - D2: 10 11 12 13\n - D3: 20 21 22 A0\n - D4: A1 A2 A3 A4\n - D0: A5 A6 A7 A8\nParity (XOR per offset o=0..3):\n- o0: 10⊕20⊕A1⊕A5 = 34\n- o1: 11⊕21⊕A2⊕A6 = 34\n- o2: 12⊕22⊕A3⊕A7 = 34\n- o3: 13⊕A0⊕A4⊕A8 = BF\n\nThus `RAID5_PARITY_STRIPE1: D1[4..7]=34,34,34,BF`.\n\nStripe 2 parity (on D2[8..11]):\n- Data after write:\n - D3: A9 AA 57 58\n - D4: 65 66 67 68\n - D0: 75 76 77 78\n - D1: 05 06 07 08\nParity:\n- o0: A9⊕65⊕75⊕05 = BC\n- o1: AA⊕66⊕76⊕06 = BC\n- o2: 57⊕67⊕77⊕07 = 40\n- o3: 58⊕68⊕78⊕08 = 40\n\nThus `RAID5_PARITY_STRIPE2: D2[8..11]=BC,BC,40,40`.\n\n---\n\n## Part C — RAID4 under the same W\n\nMapping under RAID4 (j on Dj; parity on D4):\n- Stripe1: D1 sector7 = A0; D2 sectors4..7 = A1..A4; D3 sectors4..7 = A5..A8\n- Stripe2: D0 sectors8..9 = A9,AA\n\n### RAID4 I/O counts\nParity disk D4 needs full parity chunks for stripe1 (4..7) and stripe2 (8..11), which are contiguous ⇒ 1 read I/O and 1 write I/O on D4.\nData disks overwritten: D1, D2, D3, D0 ⇒ 4 reads and 4 writes.\nTotals: reads=5, writes=5.\n\nSo: `WRITE_W_IO_RAID4: reads=5 writes=5`.\n\n### RAID4 parity after W\nStripe1 parity D4[4..7]:\n- D0: 01 02 03 04\n- D1: 05 06 07 A0\n- D2: A1 A2 A3 A4\n- D3: A5 A6 A7 A8\nParity: `00,00,00,A8`\n\nStripe2 parity D4[8..11]:\n- D0: A9 AA 23 24\n- D1: 25 26 27 28\n- D2: 29 2A 2B 2C\n- D3: 2D 2E 2F 30\nParity: `88,88,00,10`\n\n---\n\n## Part D — RAID5 rebuild byte (after W), D2 failed\nNeed stripe1, j=0, o=1 (this is D2 offset1). Reconstruct:\nmissing = parity ⊕ other three data bytes.\nAt stripe1 offset1: parity=34, other data: D3=21, D4=A2, D0=A6.\n34⊕21=15; 15⊕A2=B7; B7⊕A6=11 ⇒ reconstructed byte `11`.\n\n---\n\n## Part E — Reliability (p=0.03), 10 decimals\nLet q=1-p=0.97.\n\n- RAID0 (5 disks): P(loss)=1-q^5.\n \\(0.97^5 = 0.8587340257\\) ⇒ P = 0.1412659743.\n- RAID5 (5 disks): loss if ≥2 fail:\n P = 1 - [q^5 + 5 p q^4].\n \\(q^4=0.8852928100\\),\n \\(5pq^4 = 5*0.03*0.8852928100 = 0.1327939215\\).\n Sum = 0.9915279472 ⇒ P = 0.0084720528.\n- RAID1 (2 disks): P(loss)=p^2=0.0009000000.\n\n---\n\n## Final 11-line Output\n\n```\nRAID5_READ_REQ1: (D0,4,4) (D2,4,4) (D3,4,8) (D4,2,6)\nRAID5_READ_REQ2: (D2,3,5) (D3,0,8) (D4,0,5)\nWRITE_W_IO_RAID5: reads=5 writes=5\nWRITE_W_IO_RAID4: reads=5 writes=5\nRAID5_PARITY_STRIPE1: D1[4..7]=34,34,34,BF\nRAID5_PARITY_STRIPE2: D2[8..11]=BC,BC,40,40\nRAID4_PARITY: stripe1 D4[4..7]=00,00,00,A8 | stripe2 D4[8..11]=88,88,00,10\nREBUILD_RAID5_D2_s1_j0_o1: 11\nP_LOSS_RAID0_5DISKS_p0.03: 0.1412659743\nP_LOSS_RAID5_5DISKS_p0.03: 0.0084720528\nP_LOSS_RAID1_2DISKS_p0.03: 0.0009000000\n```\n"}
{"domain": "Machine Learning & Artificial Intelligence", "prompt": "Output exactly one decimal number with exactly four digits after the decimal point.\n\nFixed data ($m=2$):\n- $x^{(1)}=[1,0]^T,\\ y^{(1)}=1$\n- $x^{(2)}=[0,1]^T,\\ y^{(2)}=0$\n\nFixed model:\n- $b=0,\\ w=[2,-2]^T$\n- $\\sigma(z)=\\frac{1}{1+e^{-z}}$\n- $z^{(i)}=w^T x^{(i)},\\ \\hat y^{(i)}=\\sigma(z^{(i)})$\n\nFor any $\\lambda>0$ define\n$$\nJ_{\\text{base},\\lambda}(w)=\\frac{1}{2}\\sum_{i=1}^{2}\\Big[-y^{(i)}\\ln(\\hat y^{(i)})-(1-y^{(i)})\\ln(1-\\hat y^{(i)})\\Big]+\\frac{\\lambda}{2}\\|w\\|_2^2.\n$$\nLet $J_{0.1}=J_{\\text{base},0.1}(w)$ and $J_{1.0}=J_{\\text{base},1.0}(w)$.\n\nConventions: $\\lfloor\\cdot\\rfloor$ is floor. For integers, $a\\bmod M$ is the unique integer in $\\{0,1,\\dots,M-1\\}$ congruent to $a$ modulo $M$. For nonnegative integers, $x>>k=\\lfloor x/2^k\\rfloor$ and $x\\ \\text{xor}\\ y$ is bitwise XOR.\n\nSet $\\epsilon=10^{-12}$.\n\nDefine\n$$\nt=\\frac{1}{2}\\sum_{i=1}^{2}\\Big[-y^{(i)}\\ln(\\hat y^{(i)})-(1-y^{(i)})\\ln(1-\\hat y^{(i)})\\Big],\n\\quad\ns=\\hat y^{(1)}(1-\\hat y^{(1)}),\n\\quad\n\\mu=0.1+\\frac{s}{2}.\n$$\nDefine the $2\\times 2$ matrix $H=\\mu I_2$ and $g=\\left[\\ 0.2-\\frac{1}{2(1+e^2)},\\ -0.2+\\frac{1}{2(1+e^2)}\\ \\right]^T$.\nDefine $\\gamma=1/\\|w\\|_2$, $R=\\max_i\\|x^{(i)}\\|_2$, and $C=R\\|w\\|_2/\\sqrt{2}$.\nDefine $\\mathrm{tr}(H)=2\\mu$ and $\\det(H)=\\mu^2$.\n\nDefine $\\Delta=0$ and $\\Omega=0$.\n\nDefine $w_\\infty^\\star=0$ and $L_\\infty=\\|w_\\infty^\\star\\|_2^2$.\nDefine $\\sigma^2>0$ by $1/\\sigma^2=0.1$.\n\nDefine bits $b_0,\\dots,b_{23}\\in\\{0,1\\}$:\n- $b_0=1$ iff $|\\Delta|\\le\\epsilon$\n- $b_1=1$ iff $\\Omega\\le\\epsilon$\n- $b_2=1$ iff $\\mu\\ge 0$\n- $b_3=1$ iff $\\|g\\|_2>0$\n- $b_4=1$ iff $|\\gamma-1/\\sqrt{8}|\\le\\epsilon$\n- $b_5=1$ iff $J_{0.1}<J_{1.0}$\n- $b_6=1$ iff $L_\\infty\\le\\epsilon$\n- $b_7=1$ iff $|0.1-1/\\sigma^2|\\le\\epsilon$\n- $b_8=1$ iff $\\lfloor 10C\\rfloor\\bmod 2=1$\n- $b_9=1$ iff $\\lfloor 1000t\\rfloor\\bmod 2=1$\n- $b_{10}=1$ iff $\\mathrm{tr}(H)>0.304$\n- $b_{11}=1$ iff $\\det(H)\\ge 0.0225$\n- $b_{12}=1$ iff $\\lfloor 10^6(\\hat y^{(1)}-0.88)\\rfloor\\bmod 2=1$\n- $b_{13}=1$ iff $\\lfloor 10^6(\\mu-0.15)\\rfloor\\bmod 2=1$\n- $b_{14}=1$ iff $(\\lfloor 10^4 t\\rfloor\\bmod 3)=0$\n- $b_{15}=1$ iff $(\\lfloor 10^6\\det(H)\\rfloor\\bmod 7)\\in\\{0,3,5\\}$\n- $b_{16}=1$ iff $(\\lfloor 10^6(\\hat y^{(2)}-0.11)\\rfloor\\bmod 2)=1$\n- $b_{17}=1$ iff $\\lfloor 10^{12}(\\hat y^{(1)}+\\hat y^{(2)}-1)\\rfloor=0$\n- $b_{18}=1$ iff $\\lfloor 10^{12}(\\mu^2-\\det(H))\\rfloor=0$\n- $b_{19}=1$ iff $\\lfloor 10^5(J_{0.1}-t)\\rfloor=40000$\n- $b_{20}=1$ iff $\\lfloor 10^{12}(C-2)\\rfloor=0$\n- $b_{21}=1$ iff $(\\lfloor 10^6(\\hat y^{(1)}-0.5)\\rfloor\\bmod 3)=1$\n- $b_{22}=1$ iff $(\\lfloor 10^6(\\hat y^{(2)}-0.1)\\rfloor\\bmod 5)\\in\\{2,4\\}$\n- $b_{23}=1$ iff $(\\lfloor 10^6(t-0.12)\\rfloor\\bmod 7)\\in\\{1,2,4\\}$\n\nPack\n$$\nP=\\sum_{k=0}^{23} b_k 2^k.\n$$\nDefine Gray and bit-reverse:\n$$\nG=P\\ \\text{xor}\\ (P>>1),\n\\quad\n\\mathrm{rev}_{24}(x)=\\sum_{j=0}^{23}\\left(\\left\\lfloor\\frac{x}{2^j}\\right\\rfloor\\bmod 2\\right)2^{23-j},\n\\quad\nR=\\mathrm{rev}_{24}(G).\n$$\n\nDefine\n$$\nS_0=(1103515245\\cdot R+12345)\\bmod 2^{31},\n\\quad\nS_1=S_0\\ \\text{xor}\\ (S_0>>11)\\ \\text{xor}\\ (S_0>>21).\n$$\nLet $M=1000000$ and set\n$$\nT_0=S_1\\bmod M,\\quad\nT_1=(17389\\cdot T_0+711)\\bmod M,\\quad\nT_2=(88411\\cdot T_1+31337)\\bmod M,\n$$\n$$\nW=(T_2\\ \\text{xor}\\ (T_2>>3)\\ \\text{xor}\\ (T_2>>9))\\bmod M.\n$$\n\nFinally define\n$$\nJ(w)=J_{0.1}+\\frac{W-500000}{1000000}.\n$$\n\nDo not round intermediate quantities. Round only the final $J(w)$ to four decimal places and output it.", "rubrics": [{"criterion": "Format: The final answer matches regex ^[0-9]+\\.[0-9]{4}?", "weight": 10}, {"criterion": "Packed signature: $P=8281343$.", "weight": 10}, {"criterion": "Gray transform: $G=4289152$.", "weight": 10}, {"criterion": "Bit reversal: $R=85634$.", "weight": 10}, {"criterion": "LCG state: $S_0=554056083$.", "weight": 10}, {"criterion": "Final mixer: $W=86388$.", "weight": 10}, {"criterion": "Final answer is exactly 0.1133.", "weight": 20}], "golden_answer": "## Step 1: core scalars\n$z^{(1)}=2,\\ z^{(2)}=-2$.\n\nLet $a=e^2$. Then\n$\\hat y^{(1)}=\\frac{a}{1+a}$ and $\\hat y^{(2)}=\\frac{1}{1+a}$, so numerically\n$\\hat y^{(1)}=0.8807970779778824\\ldots$ and $\\hat y^{(2)}=0.1192029220221176\\ldots$.\n\nBoth per-sample losses equal $\\ln(1+e^{-2})$, hence\n$t=\\ln(1+e^{-2})=0.1269280110429725\\ldots$.\n\n$\\|w\\|_2^2=8$, so $J_{0.1}=t+0.4$ and $J_{1.0}=t+4.0$, hence $J_{0.1}<J_{1.0}$.\n\n$s=\\hat y^{(1)}(1-\\hat y^{(1)})=\\frac{a}{(1+a)^2}=0.1049935854035065\\ldots$.\n\n$\\mu=0.1+s/2=0.1524967927017532\\ldots$, so $H=\\mu I_2$ and $\\mathrm{tr}(H)=2\\mu>0.304$, $\\det(H)=\\mu^2\\ge 0.0225$.\n\n$\\gamma=1/\\|w\\|_2=1/\\sqrt{8}$, $R=1$, $C=R\\|w\\|_2/\\sqrt{2}=2$.\n\n$\\Delta=0,\\ \\Omega=0,\\ w_\\infty^\\star=0,\\ L_\\infty=0,\\ 1/\\sigma^2=0.1$.\n\n## Step 2: the 24 bits\nFrom the above:\n$b_0=b_1=b_2=b_3=b_4=b_5=b_6=b_7=1$,\n$b_8=0$ (since $\\lfloor 10C\\rfloor=20$),\n$b_9=0$ (since $\\lfloor 1000t\\rfloor=126$),\n$b_{10}=1$, $b_{11}=1$.\n\n$b_{12}=1$ since $\\lfloor 10^6(\\hat y^{(1)}-0.88)\\rfloor=\\lfloor 797.0779\\ldots\\rfloor=797$ is odd.\n\n$b_{13}=0$ since $\\lfloor 10^6(\\mu-0.15)\\rfloor=\\lfloor 2496.7927\\ldots\\rfloor=2496$ is even.\n\n$b_{14}=1$ since $\\lfloor 10^4 t\\rfloor=\\lfloor 1269.2801\\ldots\\rfloor=1269$ and $1269\\bmod 3=0$.\n\n$b_{15}=0$ since $\\lfloor 10^6\\det(H)\\rfloor=\\lfloor 23255.27\\ldots\\rfloor=23255$ and $23255\\bmod 7=1\\notin\\{0,3,5\\}$.\n\n$b_{16}=0$ since $\\lfloor 10^6(\\hat y^{(2)}-0.11)\\rfloor=\\lfloor 9202.9220\\ldots\\rfloor=9202$ is even.\n\n$b_{17}=1$ since $\\hat y^{(1)}+\\hat y^{(2)}=1$ exactly.\n$b_{18}=1$ since $\\det(H)=\\mu^2$ exactly.\n$b_{19}=1$ since $J_{0.1}-t=0.4$ so $\\lfloor 10^5(J_{0.1}-t)\\rfloor=40000$.\n$b_{20}=1$ since $C=2$ exactly.\n\n$b_{21}=1$ since $\\lfloor 10^6(\\hat y^{(1)}-0.5)\\rfloor=\\lfloor 380797.0779\\ldots\\rfloor=380797$ and $380797\\bmod 3=1$.\n$b_{22}=1$ since $\\lfloor 10^6(\\hat y^{(2)}-0.1)\\rfloor=\\lfloor 19202.9220\\ldots\\rfloor=19202$ and $19202\\bmod 5=2\\in\\{2,4\\}$.\n$b_{23}=0$ since $\\lfloor 10^6(t-0.12)\\rfloor=\\lfloor 6928.0110\\ldots\\rfloor=6928$ and $6928\\bmod 7=5\\notin\\{1,2,4\\}$.\n\nSo $(b_0,\\ldots,b_{23})=(1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,0,0,1,1,1,1,1,1,0)$.\n\n## Step 3: pack to P\nCompute\n$P=\\sum_{k=0}^{23} b_k 2^k=8281343$.\n\n## Step 4: Gray and reverse\n$G=P\\ \\text{xor}\\ (P>>1)=4289152$.\n\n$R=\\mathrm{rev}_{24}(G)=85634$.\n\n## Step 5: LCG and mixers\n$S_0=(1103515245\\cdot R+12345)\\bmod 2^{31}=554056083$.\n\n$S_1=S_0\\ \\text{xor}\\ (S_0>>11)\\ \\text{xor}\\ (S_0>>21)=553785436$.\n\nWith $M=1000000$:\n$T_0=S_1\\bmod M=785436$,\n$T_1=(17389\\cdot T_0+711)\\bmod M=947315$,\n$T_2=(88411\\cdot T_1+31337)\\bmod M=97802$.\n\n$W=(T_2\\ \\text{xor}\\ (T_2>>3)\\ \\text{xor}\\ (T_2>>9))\\bmod M=86388$.\n\n## Step 6: final scalar\n$J_{0.1}=t+0.4=\\ln(1+e^{-2})+0.4$.\n\nThus\n$J(w)=J_{0.1}+\\frac{W-500000}{1000000}=\\ln(1+e^{-2})+0.4+\\frac{86388-500000}{1000000}$,\nso\n$J(w)=\\ln(1+e^{-2})-0.013612$.\n\nNumerically,\n$J(w)=0.1133160110429726\\ldots$,\nso rounded to four decimals it is $0.1133$.\n\n## GTFA\n0.1133"}
{"domain": "Algorithms & Data Structures", "prompt": "## Edge-interval cactus counting\n\nYou have an undirected graph on `N` vertices with `M` edges in a fixed order `E1..EM`.\n\nA connected component is **cactus-like** if every edge belongs to at most one simple cycle. \nThe graph is **dune-stable** if each connected component is cactus-like.\n\nCount pairs `(L, R)` with `1 ≤ L ≤ R ≤ M` such that the subgraph using only edges\n`EL, EL+1, …, ER` is dune-stable.\n\n### Input\n- Two integers `N` and `M`\n- Then `M` lines, the endpoints of edge `Ei`\n\n### Output\n- One integer, the number of valid `(L, R)` pairs\n", "rubrics": [{"criterion": "Does the response define a dune-stable graph as one whose every connected component is cactus-like?", "weight": 10}, {"criterion": "Does the response state that dune-stability is preserved under deleting edges?", "weight": 10}, {"criterion": "Does the response state that for each fixed L, the number of valid intervals starting at L equals R - L + 1 after maximizing R?", "weight": 10}, {"criterion": "Does the response describe the edge-as-vertex transformation by introducing a vertex mid(e) for each original edge e?", "weight": 10}, {"criterion": "Does the response state the invariant that each simple cycle has exactly one non-tree edge excluded from the maintained spanning forest?", "weight": 10}, {"criterion": "Does the response state that inserting an edge that closes a cycle is rejected when the tree path between its endpoints contains a used-marked edge?", "weight": 10}, {"criterion": "Does the response state that the excluded non-tree edge for a newly formed cycle is chosen as the minimum-index edge on that cycle?", "weight": 10}, {"criterion": "Does the response state that marking cycle edges is implemented by a lazy path update that sets used to 1 on a link-cut tree path?", "weight": 10}, {"criterion": "Does the response state that deleting an excluded non-tree cycle edge triggers a path update that sets used to 0 on the path between its endpoints?", "weight": 10}, {"criterion": "Does the response state that deleting a tree edge is handled by cutting it from the maintained spanning forest?", "weight": 10}], "golden_answer": "## Expert solution \n\n**Terminology.** The prompt calls a graph **dune-stable** if every connected component is cactus-like (each edge lies on at most one simple cycle). I will refer to this same property as **desert** below: **desert ⇔ dune-stable**.\n\n### Monotonicity (enables two pointers)\n- If a graph is desert (dune-stable), **deleting edges** cannot create a violation, so it stays desert. \n- If a graph is **not** desert, **adding edges** cannot fix the existence of an edge that already lies on two different simple cycles, so it stays not desert. \n\nTherefore, for each fixed `L` there exists a maximal `R(L)` such that the window `[L..R(L)]` is desert, and all `[L..R]` with `R ≤ R(L)` are also desert.\n\n### Two pointers and counting formula\nMaintain a sliding window `[L..R]` that is always desert. For each `L`:\n1. Extend `R` as far as possible while keeping the window desert.\n2. Once `R` is maximal, the number of valid pairs starting at `L` equals **`R − L + 1`**.\n3. Add **`R − L + 1`** to the answer.\n4. Remove edge `E_L` and increment `L`.\n\n### Invariant: spanning forest with “one excluded edge per cycle”\nMaintain a spanning forest of the current window graph.\n\nIn a cactus component, every simple cycle is represented by:\n- exactly one **special** cycle edge that is **not** in the spanning tree, and\n- all other edges of the cycle are tree edges marked `used = 1` (“this tree edge already belongs to a cycle”).\n\n### Link-Cut Tree (LCT) edge-as-vertex modeling\nBecause an LCT stores data on vertices, represent each original edge `e_i = (u, v)` by creating a new vertex `mid(i)`. \nConnect `u—mid(i)` and `mid(i)—v` in the LCT when the edge is in the spanning forest.\n\nStore metadata on `mid(i)`:\n- `idx(mid(i)) = i`\n- `used(mid(i)) ∈ {0,1}`\n\nMaintain path aggregates over edge-vertices:\n- `minIdx` on a path (minimum `idx` among edge-vertices on the path)\n- `maxUsed` on a path (maximum `used` among edge-vertices on the path)\n\nUse lazy propagation to assign `used := 0` or `used := 1` on all edge-vertices along an LCT path.\n\n### Insert edge `e_i = (u, v)` at the right boundary\nLet `x = u`, `y = v`, and let `mid(i)` be the edge-vertex.\n\n**Case A: `x` and `y` are disconnected.**\n- Link `x—mid(i)—y` into the forest.\n- No cycle is created.\n\n**Case B: `x` and `y` are already connected.**\n- The unique tree path `P(x, y)` plus the new edge forms one simple cycle.\n- Query `maxUsed` on `P(x, y)`.\n - If `maxUsed = 1`, adding this edge would force an edge to lie on two cycles → window becomes invalid.\n - If `maxUsed = 0`, the cycle is allowed.\n\n**Choosing the special excluded edge**\n- The cycle edges are exactly: edges on `P(x, y)` plus the new edge `i`.\n- Since edges are appended in increasing index order, `i` is the largest index on the cycle.\n- Therefore the smallest-index cycle edge is the minimum `idx` on `P(x, y)`, obtainable by an LCT path-min query.\n\n**Update**\n- Cut that minimum-index edge-vertex from the spanning tree (it becomes the special excluded edge).\n- Link `x—mid(i)—y` into the spanning tree.\n- Apply a lazy path update `used := 1` on `P(x, y)` in the new tree.\n\n### Delete edge `E_L` when moving the left boundary\nTrack for each edge whether it is currently linked in the spanning forest (tree edge) or excluded as the special non-tree edge.\n\n- If `E_L` is the special excluded non-tree edge:\n - Deleting it destroys that cycle.\n - Apply a lazy path update `used := 0` on the tree path between its endpoints.\n\n- If `E_L` is a tree edge:\n - Cut its edge-vertex `mid(L)` from the spanning forest.\n\n### Complexity justification\nEach insertion/deletion performs a constant number of LCT operations (path query, path update, link, cut). \nEach LCT operation is `O(log N)` amortized. \nTwo pointers performs `O(M)` insertions and `O(M)` deletions total. \nTotal time: **`O(M log N)`**.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "## Scenario\nA corridor contains `n` unstable modules placed in a straight line, indexed from `1` to `n`. \nModule `i` has an **activation radius** `a[i]`.\n\nYou may **manually trigger** a module only if it is still intact. Triggering module `i` instantly destroys every module `j` satisfying:\n\n\\[\n|i - j| < a[i]\n\\]\n\nDestroyed modules cannot be triggered later. Some modules are inert with `a[i] = 0`, which means they cannot be triggered at all.\n\nYour goal is to destroy **all** modules using the **fewest manual triggers**, or determine that it cannot be done.\n\n---\n\n## Input\nThe first line contains an integer `t` — the number of test cases.\n\nFor each test case:\n- The first line contains `n` — the number of modules.\n- The second line contains `n` integers `a[1], a[2], ..., a[n]`.\n\n### Constraints\n- \\(1 \\le t \\le 10^4\\)\n- \\(2 \\le n \\le 5 \\cdot 10^5\\)\n- \\(0 \\le a[i] \\le n\\)\n- The sum of `n` across all test cases is at most \\(5 \\cdot 10^5\\)\n\n---\n\n## Output\nFor each test case:\n\n- Print `-1` if it is impossible to destroy all modules.\n\nOtherwise print two lines:\n1. An integer `k` — the minimum number of triggers.\n2. `k` integers `p1 p2 ... pk` — a sequence of module indices to trigger, in the order you will trigger them.\n\nIf multiple optimal solutions exist, print any.\n", "rubrics": [{"criterion": "Does the response define the destroyed interval of triggering index i as Li = i - a[i] + 1 and Ri = i + a[i] - 1?", "weight": 10}, {"criterion": "Does the response state that indices with a[i] = 0 cannot be triggered?", "weight": 10}, {"criterion": "Does the response define dp[i] using Ri as the farthest-right destroyed position represented by state i?", "weight": 10}, {"criterion": "Does the response specify Pattern A as a range-min query over endpoints x in [Li - 1, i - 1]?", "weight": 10}, {"criterion": "Does the response specify Pattern B as a range-min query over endpoints x in [Li - 1, Ri] evaluated using only centers up to Li - 1?", "weight": 10}, {"criterion": "Does the response include an offline scheduling mechanism that executes Pattern B queries at sweep time Li - 1?", "weight": 10}, {"criterion": "Does the response perform a point update of the segment tree at position Ri with the value dp[i]?", "weight": 10}, {"criterion": "Does the response select the final answer using min dp[i] over indices satisfying Ri >= n?", "weight": 10}, {"criterion": "Does the response describe reconstruction using a predecessor pointer pre[i] obtained from the argmin returned by the segment tree query?", "weight": 10}, {"criterion": "Does the response justify sorting the reconstructed triggers by nondecreasing a[i] using an adjacent-swap validity argument based on |x-y| >= a[x]?", "weight": 10}], "golden_answer": "## Key transformation\nTriggering module `i` (only possible when `a[i] > 0`) destroys exactly the interval:\n\n- \\(L_i = i - a[i] + 1\\)\n- \\(R_i = i + a[i] - 1\\)\n\nSo each trigger corresponds to a closed range \\([L_i, R_i]\\).\n\nThe difficulty is that a module cannot be triggered after it has been destroyed, so the final set of triggered indices must admit some valid triggering order.\n\n---\n\n## DP state (compressed)\nWe only keep DP states where the **rightmost-triggered index is also the one that reaches farthest right**.\n\nLet:\n\n- `dp[i]` = minimum number of triggers needed so that, after executing them in some valid order, **all modules in `[1..R_i]` are destroyed**, and among the triggers used:\n - `i` is the **largest index**\n - `R_i` is the **maximum right endpoint** achieved\n\nIf `a[i] = 0`, then `dp[i] = +∞` since `i` cannot be triggered.\n\n---\n\n## Two valid transition patterns into `i`\nLet \\(L_i = i - a[i] + 1\\) and note \\(L_i - 1 = i - a[i]\\).\n\nWe want to combine an earlier solution (represented by some endpoint `x`) with triggering `i` to achieve coverage up to `R_i`.\n\n### Pattern A: trigger `i` after the earlier plan\nTo ensure `i` is still alive when it is triggered, the earlier plan must not destroy position `i`, which is guaranteed if the earlier plan’s farthest endpoint `x` satisfies:\n\n- \\(x < i\\)\n\nTo ensure everything up to `L_i - 1` is already destroyed before triggering `i`, we need:\n\n- \\(x \\ge L_i - 1\\)\n\nSo we need:\n\n- \\(x \\in [L_i - 1,\\; i - 1]\\)\n\n### Pattern B: trigger `i` before finishing the earlier plan\nIf we trigger `i` earlier, we are allowed to use triggers strictly left of `L_i` later (their centers are not destroyed by `i` because `i` only destroys from `L_i` onwards). \nSo we can combine with an earlier plan that only uses centers in `[1..L_i-1]`, as long as that plan already guarantees destruction of `[1..L_i-1]`, meaning its endpoint `x` satisfies:\n\n- \\(x \\ge L_i - 1\\)\n\nAlso, we only need `x` up to `R_i` in this transition layer, because `dp[i]` stores states whose farthest-right reach is `R_i`:\n\n- \\(x \\in [L_i - 1,\\; R_i]\\)\n\n---\n\n## Segment tree acceleration\nMaintain a segment tree over endpoints `pos = 1..n`.\n\nAt any sweep moment, the segment tree stores at each `pos` the best pair:\n\n- `(min_triggers_to_destroy_[1..pos], argmin_index)`\n\nWhenever we have computed `dp[i]`, we perform a point update:\n\n- `tree[R_i] = min(tree[R_i], (dp[i], i))`\n\nThis encodes: “there exists a plan with cost `dp[i]` whose farthest destroyed position is exactly `R_i` and whose representative rightmost trigger is `i`.”\n\n### Getting transition values\nFor `dp[i]`, we need:\n\n- `bestA = rangeMinQuery(L_i - 1, i - 1)` using all processed triggers up to `i-1`\n- `bestB = rangeMinQuery(L_i - 1, R_i)` but **using only triggers with index ≤ (L_i - 1)**\n\nTo implement Pattern B, do it offline:\n- For every `i`, schedule its Pattern B query to be executed at sweep time `time = L_i - 1`.\n- Pattern A query can be executed at sweep time `time = i - 1`.\n\nLet:\n- `valA` be the numeric min from Pattern A query\n- `valB` be the numeric min from Pattern B query\n\nThen:\n- `dp[i] = 1 + min(valA, valB)`\n- If both are `+∞`, then `dp[i] = +∞`.\n\nBase case:\n- A plan of cost `0` that has destroyed nothing is represented by endpoint `0`. \n Practically, initialize the structure so that querying includes the possibility of starting fresh when `L_i <= 1`, by treating `endpoint 0` as cost `0` (often implemented via shifting indices or a special-case).\n\n---\n\n## Choosing the optimal finish\nThe whole line is destroyed if some chosen trigger `i` satisfies:\n\n- \\(R_i \\ge n\\)\n\nAnswer cost:\n- \\(\\min_{i: R_i \\ge n} dp[i]\\)\n\nIf this minimum is `+∞`, print `-1`.\n\n---\n\n## Reconstruction\nStore a predecessor pointer for each `i`:\n- `pre[i]` = the `argmin_index` returned by the query that attained `min(valA, valB)` for `dp[i]`\n- If the best came from the base case, use `pre[i] = 0`\n\nPick `best_end` = an index `i*` with minimal `dp[i]` among those with `R_i >= n`, then follow `pre[]` backwards to list all triggered indices.\n\n---\n\n## Output order (valid triggering sequence)\nAfter reconstructing the set of indices, output them in **nondecreasing `a[i]`**.\n\nJustification by swap argument:\n- Consider two consecutive triggers `x` then `y` in a valid sequence with `a[x] > a[y]`.\n- Since `y` was alive when triggered, `x` did not destroy `y`, so \\(|x-y| \\ge a[x]\\).\n- Then \\(|x-y| \\ge a[x] > a[y]\\), so `y` would not destroy `x` either.\n- Swapping `x` and `y` preserves validity.\n- Repeating removes all inversions, producing a valid order sorted by `a[i]`.\n\n---\n\n## Complexity\n- Segment tree operations: \\(O(n \\log n)\\) per test file total across all tests due to sum of `n`\n- Memory: \\(O(n)\\)\n"}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem\n\nThere are `n` communication towers (numbered `1..n`) and `m` bidirectional wires.\n\nTower `i` accepts all integer frequencies in the interval `[l[i], r[i]]` (inclusive).\n\nA tower `b` is called **accessible** from tower `a` if there exists an integer frequency `x` and a sequence of towers\n`a = v1, v2, ..., vk = b`\nsuch that:\n- each consecutive pair `(vj, vj+1)` is connected by a wire, and\n- **every** tower on the sequence accepts frequency `x` (i.e., `l[vj] ≤ x ≤ r[vj]` for all `j`).\n\nImportant: accessibility is **not transitive** because the frequency `x` may differ between different paths.\n\n### Task\nOutput all towers that are accessible from tower `1`, in increasing order.\n\n### Input\n- First line: `n m` (`1 ≤ n ≤ 2⋅10^5`, `0 ≤ m ≤ 4⋅10^5`)\n- Next `n` lines: `l[i] r[i]` (`1 ≤ l[i] ≤ r[i] ≤ 2⋅10^5`)\n- Next `m` lines: undirected edges `v u` (`1 ≤ v,u ≤ n`, `v ≠ u`), no multi-edges.\n\n### Output\nPrint the accessible tower indices from `1` in ascending order.\n\n### Required sanity-checks (answer must also satisfy these)\nYour approach must produce the following outputs on these additional testcases:\n\n**Sanity Check A**\n5 4\n2 4\n3 3\n1 2\n2 3\n4 5\n1 3\n3 4\n4 2\n1 5\n\nExpected output:\n1 3 4 5\n\n**Sanity Check B**\n6 6\n1 3\n2 4\n3 5\n1 1\n4 6\n2 2\n1 2\n2 3\n3 5\n1 4\n2 6\n6 5\n\nExpected output:\n1 2 3 4 6", "rubrics": [{"criterion": "The answer explicitly restates that accessibility from tower 1 means: there exists a single integer frequency x such that all towers on the path accept x.", "weight": 10}, {"criterion": "The answer reduces the problem to taking the union over frequencies x of the connected component of node 1 in the subgraph induced by towers active at x.", "weight": 10}, {"criterion": "The answer defines the active interval of an edge (u,v) as [max(lu,lv), min(ru,rv)] and states the edge is usable exactly for x in that interval.", "weight": 10}, {"criterion": "The answer uses an offline dynamic connectivity approach over x=1..MAX that adds each edge interval into a segment tree (or equivalent divide-and-conquer) over time.", "weight": 10}, {"criterion": "The answer explicitly uses a DSU with rollback (persistent/undoable union-find) during the segment-tree traversal.", "weight": 10}, {"criterion": "The answer states that at a leaf time x where tower 1 is inactive (x not in [l1,r1]), no towers should be marked/reported from that x.", "weight": 10}, {"criterion": "The answer describes creating a merge-DAG (or DSU merge tree) where each union creates a new node with directed edges to the two merged component-nodes.", "weight": 10}, {"criterion": "The answer states that a tower v is in the final output iff the singleton node for v is reachable from at least one marked component-node corresponding to find(1) at some x.", "weight": 10}, {"criterion": "For the explicit input Sanity Check A: \\\"5 4\\\\n2 4\\\\n3 3\\\\n1 2\\\\n2 3\\\\n4 5\\\\n1 3\\\\n3 4\\\\n4 2\\\\n1 5\\\\n\\\" the answer states the output is exactly \\\"1 3 4 5\\\".", "weight": 10}, {"criterion": "For the explicit input Sanity Check B: \\\"6 6\\\\n1 3\\\\n2 4\\\\n3 5\\\\n1 1\\\\n4 6\\\\n2 2\\\\n1 2\\\\n2 3\\\\n3 5\\\\n1 4\\\\n2 6\\\\n6 5\\\\n\\\" the answer states the output is exactly \\\"1 2 3 4 6\\\".", "weight": 10}], "golden_answer": "### Key reformulation: union over frequencies of the component of tower 1\n\nFix an integer frequency `x`. Let `Active(x) = { i : l[i] ≤ x ≤ r[i] }`, and consider the subgraph induced by `Active(x)`.\nFor this `x`, the towers accessible from `1` using frequency `x` are exactly the vertices in the connected component of `1`\nin that induced subgraph (and if `1 ∉ Active(x)`, then nothing is accessible for that `x`).\n\nSo the final answer is the union over all `x` (from 1 to `MAX = 2⋅10^5`) of `Comp1(x)`.\n\nThis is an offline dynamic connectivity problem over time `x` where edges are active on intervals.\n\n---\n\n### Step 1: Convert vertex activity to edge activity intervals\n\nAn undirected wire `(u,v)` can be used at frequency `x` iff both endpoints accept `x`, i.e.:\n- `x ∈ [l[u], r[u]] ∩ [l[v], r[v]]`\n\nSo the edge `(u,v)` is active on the (possibly empty) integer interval:\n\\[\nI_{uv} = [ \\max(l[u],l[v]),\\ \\min(r[u],r[v]) ].\n\\]\nIf `I_{uv}` is non-empty, then across all `x ∈ I_{uv}`, union-find should have `u` and `v` connected.\n\nWe also only care about times `x` where tower `1` is active, i.e. `x ∈ [l[1], r[1]]`, but it’s simplest to compute everything and ignore leaves where `1` is inactive.\n\n---\n\n### Step 2: Offline dynamic connectivity by divide-and-conquer + DSU rollback\n\nUse a segment tree (or recursive divide-and-conquer) over the time axis `x ∈ [1..MAX]`.\n\nFor each edge `(u,v)` with active interval `[L,R] = I_{uv}`, add it to the segment tree nodes that fully cover `[L,R]`\n(standard “add interval to segment tree” technique). Total inserts are `O(m log MAX)`.\n\nTraverse the segment tree with a DSU that supports rollback:\n- At each node, apply (union) all edges stored in that node.\n- Recurse to children.\n- Roll back DSU to the previous snapshot when returning.\n\nAt a leaf corresponding to a single frequency `x`, DSU represents connectivity of the active-edge graph at that `x`.\n\n---\n\n### Step 3: Record all components containing vertex 1 without enumerating vertices per leaf\n\nDirectly listing all vertices in the DSU component of `1` at each `x` is too slow.\n\nInstead, build a **component-merge DAG** during DSU unions:\n\n- Create a “component node” for every original vertex `v` (a leaf node representing the singleton component `{v}`).\n- Whenever DSU unions two components with roots `ra` and `rb`, create a new DAG node `new`,\n add directed edges `new -> node(ra)` and `new -> node(rb)`,\n and set `node(newRoot) = new` as the representative DAG node for the merged DSU component.\n\nThis is a standard way to persist a history of merges; the DAG is a forest of merge trees (a “DSU merge tree”).\n\nNow, whenever we are at a leaf time `x` such that tower `1` is active (`l[1] ≤ x ≤ r[1]`), we record the current DAG representative:\n- `mark node( find(1) )`.\n\nA tower `v` is accessible from `1` iff the singleton node for `v` is reachable from at least one marked node in this merge DAG.\n\nSo after processing all leaves, run a DFS/BFS from all marked nodes in the merge DAG and mark all reachable singleton nodes.\nOutput the corresponding vertex indices.\n\n---\n\n### Correctness sketch\n\n- For any `x`, DSU at leaf `x` equals the connected components of the graph containing exactly edges whose `I_{uv}` covers `x`,\n which is exactly the induced subgraph on towers that accept `x` (edges exist iff both endpoints accept `x`).\n- Thus the DSU component of `1` at leaf `x` is exactly `Comp1(x)`.\n- Marking the DSU-component DAG node at each such `x` and then taking reachability down the merge DAG recovers the union of all\n vertices that ever belonged to `Comp1(x)` for some `x`.\n\n---\n\n### Complexity\n\n- Building edge intervals: `O(n + m)`\n- Segment tree interval insertion: `O(m log MAX)` with `MAX = 2⋅10^5`\n- DSU rollback traversal: `O((m log MAX) α(n))` amortized (each inserted edge causes one union on each visited node)\n- Merge DAG size: `O(n + number_of_unions)` = `O(n + m log MAX)`\n- Final DFS on merge DAG: linear in DAG size.\n\nThis fits the constraints.\n\n---\n\n### Sanity checks (why the expected outputs match)\n\n- Sanity A:\n - Frequency `x=2` connects 1–3–4, so {1,3,4} reachable.\n - Frequency `x=4` connects 1–5, so {1,5} reachable.\n - Union is {1,3,4,5}.\n\n- Sanity B:\n - `x=1` gives {1,4}.\n - `x=2` gives {1,2,6}.\n - `x=3` gives {1,2,3}.\n - Union is {1,2,3,4,6}.\n"}
{"domain": "Machine Learning & Artificial Intelligence", "prompt": "Can you prove that, for both (i) learning intervals on [0,1] under the uniform distribution and (ii) learning a linear separator in ℝᵈ under the uniform distribution on the unit sphere, any active learning algorithm requires Ω(d log(1/ε)) label requests to achieve error at most ε with probability ≥ 1/2 — and in particular, show that for each setting, there exists a distribution over target functions such that any algorithm making fewer than c·d log(1/ε) queries (for some constant c > 0) must output a hypothesis with error ≥ ε with probability at least 1/2?", "rubrics": [{"criterion": "Does the solution include a formula connecting query complexity k to packing size M (k ≥ log₂ M - 1)?", "weight": 10}, {"criterion": "Does the solution explain that a deterministic algorithm with k queries can produce at most 2ᵏ distinct outputs?", "weight": 10}, {"criterion": "Does the solution explain that each output hypothesis can cover at most one target in Θ?", "weight": 10}, {"criterion": "Does the solution explicitly invoke Yao’s Minimax Principle?", "weight": 10}, {"criterion": "Does the solution specify the grid spacing δ in terms of ε?", "weight": 10}, {"criterion": "Does the solution show that the symmetric difference between any two intervals in Θ is ≥ δ > 2ε?", "weight": 10}, {"criterion": "Does the solution apply the Packing Lemma to derive k = Ω(d log(1/ε)) for intervals?", "weight": 10}, {"criterion": "Does the solution specify the angular separation γ ≈ ε needed to guarantee error > 2ε?", "weight": 20}, {"criterion": "Does the solution conclude that any algorithm requires Ω(d log(1/ε)) queries for error ≤ ε with probability ≥ 1/2?", "weight": 10}], "golden_answer": "### Theorem\nFor both settings—(i) learning intervals on $[0,1]$ and (ii) learning linear separators in $\\mathbb{R}^d$—there exists a distribution over target functions such that any active learning algorithm (randomized or deterministic) requires $\\Omega(d \\log(1/\\varepsilon))$ label requests to achieve error $\\le \\varepsilon$ with probability $\\ge 1/2$.\n\n---\n\n### 1. General Framework: The Packing Lower Bound\n\nTo prove a lower bound for *any* algorithm (including randomized ones), we use **Yao’s Minimax Principle**. It implies that the worst-case error probability of a randomized algorithm is lower-bounded by the expected error probability of the best *deterministic* algorithm against a specific \"hard\" input distribution $\\mathcal{P}$.\n\nWe construct $\\mathcal{P}$ as a uniform distribution over a finite set of \"packed\" hypotheses.\n\n**Lemma (The Packing Bound):**\nLet $\\Theta = \\{h_1, \\dots, h_M\\}$ be a finite set of hypotheses such that for any distinct pair $h_i, h_j \\in \\Theta$, the **disagreement probability under the data distribution** is $d(h_i, h_j) = P_{x \\sim \\mathcal{D}}(h_i(x) \\neq h_j(x)) > 2\\varepsilon$.\nIf the target $h^*$ is chosen uniformly from $\\Theta$, then any deterministic active learning algorithm making fewer than $\\lfloor \\log_2 M \\rfloor - 1$ queries will output a hypothesis with error $> \\varepsilon$ with probability $\\ge 1/2$.\n\n**Proof of Lemma:**\n1. **Disjoint Error Regions:** Since the pairwise disagreement probability between targets is $> 2\\varepsilon$, the error balls $B(h_i, \\varepsilon) = \\{h \\mid d(h, h_i) \\le \\varepsilon\\}$ are disjoint.\n2. **Injectivity:** Consequently, any single hypothesis $\\hat{h}$ output by the learner can fall into the $\\varepsilon$-ball of **at most one** target in $\\Theta$.\n3. **Decision Tree Capacity:** A deterministic algorithm making $k$ binary queries can be modeled as a decision tree with at most $2^k$ leaves. Let $\\mathcal{L}$ be the set of hypotheses output at these leaves.\n4. **Counting:** The algorithm succeeds if the true target $h^*$ corresponds to a leaf that \"covers\" it. Since $|\\mathcal{L}| \\le 2^k$ and each leaf covers at most 1 target, the algorithm can succeed on at most $2^k$ of the $M$ possible targets.\n5. **Probability:** Under the uniform distribution over $\\Theta$, the probability of success is at most $2^k / M$. For the error probability to be $< 1/2$, we require $2^k / M > 1/2$, or $k > \\log_2 M - 1$.\n\n---\n\n### 2. Part (i): Intervals on $[0,1]$\n\n**Setting:**\n* Instance space $X = [0,1]$, Uniform distribution.\n* Hypothesis class $\\mathcal{H} = \\{ [a, b] \\mid 0 \\le a \\le b \\le 1 \\}$.\n* Problem dimension $d=2$ (two parameters).\n\n**Proof:**\nWe invoke the Packing Lemma by constructing a set $\\Theta$ of size $\\approx (1/\\varepsilon)^2$.\n\n1. **Construction:**\n Let $\\delta = 3\\varepsilon$. We define a grid of possible endpoints:\n * Left endpoints $L = \\{ 0, \\delta, 2\\delta, \\dots \\} \\cap [0, 1/2]$.\n * Right endpoints $R = \\{ 1, 1-\\delta, 1-2\\delta, \\dots \\} \\cap [1/2, 1]$.\n * Let $\\Theta = \\{ [l, r] \\mid l \\in L, r \\in R \\}$.\n * *Note:* The restriction to $[0, 1/2]$ and $[1/2, 1]$ ensures $l \\le r$ for all pairs, making all intervals valid.\n\n2. **Separation:**\n For any two distinct intervals $h_1 = [l_1, r_1]$ and $h_2 = [l_2, r_2]$, the disagreement probability (measure of the symmetric difference) is:\n $$ d(h_1, h_2) = |l_1 - l_2| + |r_1 - r_2| $$\n Since $h_1 \\neq h_2$, they must differ by at least one grid step $\\delta$ in either the left or right coordinate. Thus, $d(h_1, h_2) \\ge \\delta = 3\\varepsilon > 2\\varepsilon$.\n\n3. **Cardinality ($M$):**\n The size of $L$ is $\\approx \\frac{1/2}{3\\varepsilon} \\propto \\frac{1}{\\varepsilon}$. Similarly, $|R| \\propto \\frac{1}{\\varepsilon}$.\n $$ M = |L| \\times |R| = \\Omega\\left(\\frac{1}{\\varepsilon^2}\\right) $$\n\n4. **Lower Bound:**\n Applying the Lemma:\n $$ k \\ge \\log_2\\left( \\frac{c}{\\varepsilon^2} \\right) \\approx 2 \\log_2\\left(\\frac{1}{\\varepsilon}\\right) $$\n Since $d=2$, this confirms **$k = \\Omega(d \\log(1/\\varepsilon))$**.\n\n---\n\n### 3. Part (ii): Linear Separators in $\\mathbb{R}^d$\n\n**Setting:**\n* Instance space $X = \\mathbb{S}^{d-1}$ (unit sphere), Uniform surface measure.\n* Hypothesis class $\\mathcal{H} = \\{ x \\mapsto \\text{sign}(w \\cdot x) \\}$.\n* Problem dimension is $d$.\n\n**Proof:**\nWe invoke the Packing Lemma by constructing a spherical code $\\Theta$ of size roughly $(1/\\varepsilon)^{d-1}$.\n\n1. **Geometry of Error:**\n For unit vectors $u, v$, the disagreement probability is exactly the normalized surface measure of the wedge between the hyperplanes defined by $u$ and $v$. This is proportional to the angle:\n $$ d(h_u, h_v) = \\frac{\\theta(u, v)}{\\pi} $$\n To ensure separation $> 2\\varepsilon$, we require angular separation $\\theta > 2\\pi\\varepsilon$.\n\n2. **Construction (Spherical Packing):**\n We need a set $\\Theta \\subset \\mathbb{S}^{d-1}$ such that every pair is separated by angle $\\gamma \\approx \\varepsilon$. The maximum size of such a set is bounded by comparing the total surface area of the sphere to the area of a spherical cap of radius $\\gamma/2$.\n Using standard bounds for spherical codes (e.g., Gilbert-Varshamov or Kabatiansky-Levenshtein), the packing number scales as:\n $$ M = \\Omega\\left( \\left(\\frac{1}{\\gamma}\\right)^{d-1} \\right) = \\Omega\\left( \\left(\\frac{1}{\\varepsilon}\\right)^{d-1} \\right) $$\n *(This holds up to constant factors in the exponent).*\n\n3. **Lower Bound:**\n Applying the Lemma:\n $$ k \\ge \\log_2 M - 1 \\approx (d-1) \\log_2 \\left(\\frac{1}{\\varepsilon}\\right) $$\n For $d \\ge 2$, we have $d-1 \\ge d/2$. Thus:\n $$ k = \\Omega\\left( d \\log \\frac{1}{\\varepsilon} \\right) $$\n\n### Conclusion\n\nIn both cases, we established that the set of distinguishable hypotheses has a size $M$ that scales as $(1/\\varepsilon)^{\\Theta(d)}$. Since active learning queries provide at most 1 bit of information per query, identifying the correct target requires $\\log_2 M$ queries.\nTherefore, any algorithm requires $\\Omega(d \\log(1/\\varepsilon))$ queries."}
{"domain": "Algorithms & Data Structures", "prompt": "You are given two positive integers **n** and **k**. For every integer **x** such that\n1 <= x <= n, write the representation of **x** in base **k** (without leading zeros).\n\nEach representation is a sequence of digits. Collect all n such digit-sequences and sort\nthem in **lexicographic order**: two sequences are compared digit by digit from left to\nright (each digit compared by its integer value); at the first position where they differ,\nthe sequence with the smaller digit comes first; if one sequence is a proper prefix of\nthe other, the shorter one comes first.\n\nAfter sorting, index the array from 1 to n (1-based indexing).\n\n**Your task:** For each test case, compute how many integers i (1 <= i <= n) satisfy the\nfollowing condition: the base-k representation of i appears **exactly at position i** in\nthe sorted array.\n\n**Additionally, describe the algorithm you use and explain why it runs efficiently for\nthe given constraints.**\n\n---\n\n### Input\n\n5\n7 2\n10 3\n100 10\n1000000000000000000 10\n1000000000000000000 2\n\n---\n\nThe number 5 inside the `Input` represents the number of test cases.\n\n### Notes\n\n- The representation of 1 in any base is the single digit [1].\n- The number 7 in base 3 is [2, 1].\n- The number 81 in base 9 is [1, 0, 0].\n- For the first test case (n=7, k=2), the base-2 representations sorted\n lexicographically are:\n [1], [1,0], [1,0,0], [1,0,1], [1,1], [1,1,0], [1,1,1]\n corresponding to decimal values 1, 2, 4, 5, 3, 6, 7.\n The values i where position equals i are: i=1 (value 1 at position 1),\n i=2 (value 2 at position 2), i=6 (value 6 at position 6),\n i=7 (value 7 at position 7). So the answer is 4.\n\n---\n\n### Output\n\nFor each test case, output a single integer on its own line: the count of values i such\nthat the base-k representation of i is located at position i in the lexicographically\nsorted array.\n", "rubrics": [{"criterion": "The response outputs 4 as the answer for the first test case (n=7, k=2).", "weight": 10}, {"criterion": "The response outputs 1 as the answer for the second test case (n=10, k=3).", "weight": 10}, {"criterion": "The response outputs 11 as the answer for the third test case (n=100, k=10).", "weight": 10}, {"criterion": "The response outputs 11 as the answer for the fourth test case (n=10^18, k=10).", "weight": 15}, {"criterion": "The response outputs 2 as the answer for the fifth test case (n=10^18, k=2).", "weight": 15}, {"criterion": "The response describes a method for computing the lexicographic rank of a number by counting how many valid numbers (at most n) are lexicographically smaller, using prefix-based or subtree-based counting.", "weight": 15}, {"criterion": "The response explains why the fixed-point solutions within each group of same-length representations form a contiguous range (or equivalently, why binary search is applicable), by arguing that the difference between lexicographic rank and numeric rank is non-decreasing within such a group.", "weight": 15}, {"criterion": "The response correctly states or demonstrates that the algorithm runs in polynomial-in-log-n time (e.g., O((log n)^2) or O((log n)^3)) per test case, making it feasible for n up to 10^18.", "weight": 10}], "golden_answer": "PROBLEM ANALYSIS\n================\n\nWe must count how many x in [1..n] satisfy: lexicographic_rank(x) = x,\nwhere lexicographic_rank(x) is the 1-based position of x's base-k\nrepresentation in the sorted array of all representations from 1 to n.\n\nKEY INSIGHT: TRIE MODEL\n========================\n\nModel all base-k representations as paths in a digit trie:\n- Root has children for digits 1..k-1 (no leading zeros)\n- Each internal node has children for digits 0..k-1\n- A node is \"active\" if the number it represents is <= n\n\nTwo traversal orders correspond to two rankings:\n- BFS (level-order): visits by increasing length, then by numeric value\n within equal length. This gives bfs_rank(x) = x for all x.\n- DFS (pre-order, children in digit order 0..k-1): visits in\n lexicographic order. This gives dfs_rank(x) = lexicographic_rank(x).\n\nTherefore we need: count of x where dfs_rank(x) = x.\n\nCOMPUTING dfs_rank(x)\n=====================\n\nGiven x with base-k digits d_1 d_2 ... d_L:\n\ndfs_rank(x) = 1 + (number of valid entries < x in lex order)\n\nAlgorithm:\n rank = 0, prefix = 0\n For each digit position i (0-indexed):\n For every digit c from start_digit to d_i - 1:\n rank += subtree_size(prefix * k + c, k, n)\n prefix = prefix * k + d_i\n If this is not the last digit and prefix <= n:\n rank += 1 (count the prefix itself as a valid number)\n Return rank + 1\n\nwhere start_digit = 1 for the first position, 0 otherwise.\n\nSUBTREE SIZE (prefix counting)\n==============================\n\nCount of numbers in [1..n] whose base-k representation starts with\na given prefix:\n\n def subtree_size(prefix, k, n):\n low, high, count = prefix, prefix + 1, 0\n while low <= n:\n count += min(n + 1, high) - low\n low *= k\n high *= k\n return count\n\nFor summing over consecutive digits c in [a, b), use:\n subtree_range_size(prefix*k + a, prefix*k + b, k, n)\nwhich avoids iterating over each digit individually (critical for large k).\n\nMONOTONICITY AND BINARY SEARCH\n==============================\n\nDefine f(x) = dfs_rank(x) - x.\n\nWithin each \"layer\" (set of numbers with the same base-k representation\nlength L), f(x) is non-decreasing. Proof: for consecutive x, x+1 in the\nsame layer, bfs_rank increases by 1 while dfs_rank increases by >= 1.\n\nConsequence: the set of solutions {x : f(x) = 0} within each layer\nforms a contiguous (possibly empty) range. We can binary search for the\nfirst and last x satisfying f(x) = 0 in each layer.\n\nFULL ALGORITHM\n==============\n\nFor each test case (n, k):\n answer = 0\n For each digit-length L = 1, 2, ...:\n Compute layer range [lo, hi] where lo = k^(L-1), hi = min(k^L - 1, n)\n (For L=1: lo=1, hi=min(k-1, n))\n If lo > n: break\n Binary search in [lo, hi] for first x with dfs_rank(x) >= x\n Binary search in [lo, hi] for last x with dfs_rank(x) <= x\n If valid range found: answer += last - first + 1\n Output answer\n\nCOMPLEXITY: O((log_k n)^2 * log(layer_size)) per test case.\n - Number of layers: O(log_k n)\n - Binary search per layer: O(log(layer_size))\n - dfs_rank: O(log_k n) with range subtree counting\nThis handles n, k up to 10^18 efficiently.\n\nVERIFICATION\n============\n\nWorking Python solution:\n\n def to_digits(x, k):\n digits = []\n while x > 0:\n digits.append(x % k)\n x //= k\n return digits[::-1]\n\n def count_range_subtrees(lo_pref, hi_pref, k, n):\n low, high, count = lo_pref, hi_pref, 0\n while low <= n:\n count += min(n + 1, high) - low\n low *= k\n high *= k\n return count\n\n def lex_rank(x, k, n):\n digits = to_digits(x, k)\n rank, prefix = 0, 0\n for i, d in enumerate(digits):\n start = 1 if i == 0 else 0\n if d > start:\n rank += count_range_subtrees(prefix*k + start, prefix*k + d, k, n)\n prefix = prefix * k + d\n if i < len(digits) - 1 and prefix <= n:\n rank += 1\n return rank + 1\n\n def solve(n, k):\n count, L = 0, 1\n while True:\n if L == 1:\n lo, hi = 1, min(k - 1, n)\n else:\n lo = k ** (L - 1)\n if lo > n: break\n hi = min(lo * k - 1, n)\n if lo > hi:\n L += 1; continue\n a, b = lo, hi; first = hi + 1\n while a <= b:\n mid = (a + b) // 2\n if lex_rank(mid, k, n) >= mid: first, b = mid, mid - 1\n else: a = mid + 1\n a, b = lo, hi; last = lo - 1\n while a <= b:\n mid = (a + b) // 2\n if lex_rank(mid, k, n) <= mid: last, a = mid, mid + 1\n else: b = mid - 1\n if first <= last: count += last - first + 1\n L += 1\n return count\n\nVerified against brute force for hundreds of random (n, k) pairs with\nn up to 500 and k up to 30.\n\nANSWERS\n=======\n\nTest case 1: n=7, k=2 => 4\nTest case 2: n=10, k=3 => 1\nTest case 3: n=100, k=10 => 11\nTest case 4: n=10^18, k=10 => 11\nTest case 5: n=10^18, k=2 => 2\n\nOutput:\n4\n1\n11\n11\n2\n```"}
{"domain": "Database Systems & Data Engineering", "prompt": "# Prompt\n\n## Database Storage\n\n### Problem Context and Objective\n\nConsider a B+ tree where each node can hold a maximum of 4 keys and 5 pointers. The tree is initially empty. The following keys are inserted into the tree one at a time, in the order shown:\n\nera, ban, bat, kin, day, log, rye, max, won, ace, ado, bug, cop, gas, let, fax\n\nUse lexicographic (dictionary) ordering to compare strings.\n\n**B+ tree insertion rules:**\n- Keys are always inserted into the appropriate leaf node.\n- When a leaf node overflows (receives a 5th key), sort all 5 keys, place the first 2 in the left node, place the last 3 in a new right node, and copy the first key of the right node up into the parent. If no parent exists, create a new root containing that single key.\n- When an internal node overflows (receives a 5th key), sort all 5 keys, place the first 2 in the left node, place the last 2 in a new right node, and push the 3rd (middle) key up into the parent. If no parent exists, create a new root.\n- In a leaf split, the promoted key is copied (it remains in the leaf). In an internal split, the promoted key is pushed up (it is removed from the child).\n\nCompute the tree utilization after every 4 insertions. Utilization is defined as:\n\n$$\\text{utilization} = \\frac{\\text{total number of keys stored across all nodes}}{4 \\times \\text{total number of nodes}}$$\n\nStore the utilization values as decimal fractions (between 0 and 1) in variables $a$, $b$, $c$, $d$ corresponding to after 4, 8, 12, and 16 insertions respectively. Round each to exactly 3 decimal places.\n\n---\n\nNow consider a separate problem. Assume we have a relation $r(X, Y)$ where the domain of $X$ is $\\{A, B, C, D\\}$ and the domain of $Y$ is integers. The hash function on $X$ is defined as follows (4-bit binary values):\n\n| Key | Hash |\n|-----|------|\n| A | 0100 |\n| B | 0101 |\n| C | 0011 |\n| D | 1101 |\n\nThe hash structure uses **prefix-based matching starting from the most significant bit (bit 1 is leftmost)**.\n\nConstruct an extendible hash structure by inserting the following records in the order shown:\n\n(B,8), (D,4), (C,1), (A,7), (D,3), (D,9), (B,5)\n\nEach bucket can hold at most 2 records.\n\n**Extendible hashing rules:**\n- Each bucket has a Local Depth (LD). The directory has a Global Depth (GD). Initially GD = 0 and there is one bucket with LD = 0.\n- When a bucket overflows: if LD < GD, increment LD and split the bucket by examining the next bit of the hash. If LD = GD, first double the directory (increment GD), then increment LD and split.\n- After a split, if all overflowing records still map to the same new bucket because their hash values share the same prefix for all bits up to the new LD, repeat the split process (doubling the directory again if needed).\n- If all records in an overflowing bucket have identical full 4-bit hash values (so no further bit can separate them), stop splitting and attach an overflow page to that bucket instead.\n\nIn the final hash structure, number the distinct buckets 1 through $N$ in the order they are first encountered when scanning the directory from binary index 0000...0 to 1111...1.\n\n---\n\n**Computation:**\n\n$$e = \\text{round}(10 \\times a \\times b \\times c \\times d)$$\n\nwhere $\\text{round}$ denotes rounding to the nearest integer.\n\nLet $N$ be the total number of distinct buckets (not counting overflow pages). Compute:\n- Bucket index $p = ((e - 1) \\bmod N)$. If $p = 0$, set $p = N$.\n- Bucket index $q = ((e + 1) \\bmod N)$. If $q = 0$, set $q = N$.\n\nCount the records in buckets $p$ and $q$ (only records in the main bucket, not in overflow pages). Compute the fraction of total records (out of 7) stored in these two buckets combined. Round to 3 decimal places.\n\n**Report the following values in your answer: $a$, $b$, $c$, $d$, $e$, and the final fraction.**", "rubrics": [{"criterion": "Does the solution report the utilization after 4 insertions as a = 1.000 (or equivalent rounding)?", "weight": 10}, {"criterion": "Does the solution report the utilization after 8 insertions as b = 0.625?", "weight": 10}, {"criterion": "Does the solution report the utilization after 12 insertions as c = 0.667?", "weight": 10}, {"criterion": "Does the solution report the utilization after 16 insertions as d = 0.833?", "weight": 10}, {"criterion": "Does the solution correctly compute the value of e as 3?", "weight": 10}, {"criterion": "Does the solution determine that the final extendible hash structure has a global depth of 4?", "weight": 15}, {"criterion": "Does the solution determine that the final extendible hash structure contains exactly 6 distinct buckets (not counting overflow pages)?", "weight": 10}, {"criterion": "Does the solution correctly apply the overflow page rule for key D, recognizing that all D records share the identical 4-bit hash 1101 and therefore cannot be separated by further splitting?", "weight": 15}, {"criterion": "Does the solution correctly determine the bucket indices p = 2 and q = 4 using modulo arithmetic with 1-based adjustment?", "weight": 10}, {"criterion": "Does the solution correctly identify the contents of bucket 2 ([(A,7)]) and bucket 4 (empty), counting only main bucket records?", "weight": 10}, {"criterion": "Does the solution output the final fraction as 0.143?", "weight": 20}], "golden_answer": "# Golden Answer\n\n## Part 1: B+ Tree Construction\n\nThe tree starts empty. Each node can hold at most 4 keys. The split rule for leaves: when a leaf has 5 keys, left gets keys at positions 1-2, right gets keys at positions 3-5, and the key at position 3 (first key of right node) is copied up to the parent.\n\n**Insertions 1-4 (era, ban, bat, kin):**\n\nInsert era: single leaf [era].\nInsert ban: leaf [ban, era] (sorted).\nInsert bat: leaf [ban, bat, era].\nInsert kin: leaf [ban, bat, era, kin].\n\nOne node, 4 keys, 4 spots.\n$a = 4/(4 \\times 1) = 4/4 = 1.000$.\n\n**Insertions 5-8 (day, log, rye, max):**\n\nInsert day into leaf [ban, bat, era, kin]. Now has 5 keys: [ban, bat, day, era, kin].\nOverflow: left = [ban, bat], right = [day, era, kin]. Copy \"day\" up to new root.\nTree: root=[day], leaves=[ban, bat] and [day, era, kin].\n\nInsert log: goes to right leaf (log > day). Right leaf becomes [day, era, kin, log]. Fits (4 keys).\n\nInsert rye: goes to right leaf. Now 5 keys: [day, era, kin, log, rye].\nOverflow: left = [day, era], right = [kin, log, rye]. Copy \"kin\" up to root.\nRoot = [day, kin]. Leaves: [ban, bat], [day, era], [kin, log, rye].\n\nInsert max: goes to rightmost leaf (max > kin). Leaf becomes [kin, log, max, rye]. Fits (4 keys).\n\nNode count: 1 root + 3 leaves = 4.\nKey count: root has 2, leaves have 2 + 2 + 4 = 8. Total = 10.\nSpots: $4 \\times 4 = 16$.\n$b = 10/16 = 0.625$.\n\n**Insertions 9-12 (won, ace, ado, bug):**\n\nInsert won: goes to rightmost leaf [kin, log, max, rye]. Now 5 keys: [kin, log, max, rye, won].\nOverflow: left = [kin, log], right = [max, rye, won]. Copy \"max\" up.\nRoot = [day, kin, max]. Leaves: [ban, bat], [day, era], [kin, log], [max, rye, won].\n\nInsert ace: goes to leftmost leaf (ace < day, ace < ban). Leaf becomes [ace, ban, bat]. Fits.\n\nInsert ado: goes to leftmost leaf. Leaf becomes [ace, ado, ban, bat]. Fits (4 keys, full).\n\nInsert bug: goes to leftmost leaf (bug > ban, bug < day). Now 5 keys: [ace, ado, ban, bat, bug].\nOverflow: left = [ace, ado], right = [ban, bat, bug]. Copy \"ban\" up.\nRoot = [ban, day, kin, max]. Leaves: [ace, ado], [ban, bat, bug], [day, era], [kin, log], [max, rye, won].\n\nNode count: 1 root + 5 leaves = 6.\nKey count: root has 4, leaves have 2 + 3 + 2 + 2 + 3 = 12. Total = 16.\nSpots: $4 \\times 6 = 24$.\n$c = 16/24 = 0.66\\overline{6} \\approx 0.667$.\n\n**Insertions 13-16 (cop, gas, let, fax):**\n\nInsert cop: goes to leaf [ban, bat, bug] (cop > ban, cop < day). Leaf becomes [ban, bat, bug, cop]. Fits (full).\n\nInsert gas: goes to leaf [day, era] (gas > day, gas < kin). Leaf becomes [day, era, gas]. Fits.\n\nInsert let: goes to leaf [kin, log] (let > kin, let < log lexicographically). Leaf becomes [kin, let, log]. Fits.\n\nInsert fax: goes to leaf [day, era, gas] (fax > day, fax < gas). Leaf becomes [day, era, fax, gas]. Fits (full).\n\nNode count: 1 root + 5 leaves = 6. (No new splits occurred.)\nKey count: root has 4, leaves have 2 + 4 + 4 + 3 + 3 = 16. Total = 20.\nSpots: $4 \\times 6 = 24$.\n$d = 20/24 = 0.83\\overline{3} \\approx 0.833$.\n\n**Summary:** $a = 1.000$, $b = 0.625$, $c = 0.667$, $d = 0.833$.\n\n---\n\n## Part 2: Extendible Hashing\n\nHash values (4-bit, MSB first): A = 0100, B = 0101, C = 0011, D = 1101.\n\n**Step 1 - Initialization:** GD = 0. One bucket (LD = 0), empty.\n\n**Step 2 - Insert (B,8):** Hash(B) = 0101. Bucket has room. Bucket: [(B,8)]. LD = 0.\n\n**Step 3 - Insert (D,4):** Hash(D) = 1101. Same bucket (GD = 0, only one directory entry). Bucket: [(B,8), (D,4)]. Now full (capacity 2). LD = 0.\n\n**Step 4 - Insert (C,1):** Hash(C) = 0011. Target bucket is full. Must split.\n- LD = GD = 0, so double directory first. GD becomes 1. Directory now has 2 entries (0 and 1).\n- Increment LD to 1. Split by bit 1:\n - B(0101) -> prefix 0 -> directory 0\n - C(0011) -> prefix 0 -> directory 0\n - D(1101) -> prefix 1 -> directory 1\n- Directory 0 -> Bucket A (LD=1): [(B,8), (C,1)] - full\n- Directory 1 -> Bucket B (LD=1): [(D,4)]\n\n**Step 5 - Insert (A,7):** Hash(A) = 0100. Prefix \"0\" -> directory 0 -> Bucket A: [(B,8), (C,1)]. Full. Must split.\n- LD = GD = 1, so double directory. GD becomes 2. Directory now has 4 entries (00, 01, 10, 11).\n- Increment LD to 2. Split Bucket A by bit 2:\n - C(0011) -> prefix 00 -> directory 00\n - B(0101) -> prefix 01 -> directory 01\n - A(0100) -> prefix 01 -> directory 01\n- Directory 00 -> Bucket C (LD=2): [(C,1)]\n- Directory 01 -> Bucket D (LD=2): [(B,8), (A,7)] - full\n- Directory 10 -> Bucket B (LD=1): [(D,4)] (unchanged, LD still 1)\n- Directory 11 -> Bucket B (LD=1): [(D,4)] (same bucket as 10)\n\n**Step 6 - Insert (D,3):** Hash(D) = 1101. Prefix \"11\" -> directory 11 -> Bucket B: [(D,4)]. Has room.\nBucket B: [(D,4), (D,3)]. Now full. LD = 1.\n\n**Step 7 - Insert (D,9):** Hash(D) = 1101. Prefix \"11\" -> directory 11 -> Bucket B: [(D,4), (D,3)]. Full. Must split.\n- LD(1) < GD(2), so no directory doubling needed. Increment LD to 2. Split by bit 2:\n - D(1101) -> prefix 11. All three D records (D,4), (D,3), (D,9) have hash 1101 -> prefix 11.\n - Directory 10 -> new Bucket E (LD=2): empty.\n - Directory 11 -> Bucket B (LD=2): All three D records still map here.\n- Bucket B still has 3 records but capacity 2. Attempt further split:\n - LD(2) = GD(2), so must double directory to split further. But all three records have identical 4-bit hash 1101. Check: can bit 3 separate them? D's bit 3 is 0 for all. Can bit 4 separate them? D's bit 4 is 1 for all. Since all records have the identical full 4-bit hash value 1101, no further splitting can separate them.\n - Create overflow page.\n- Directory 11 -> Bucket B (LD=2): [(D,4), (D,3)] + overflow page: [(D,9)]\n\nState after step 7:\n- 00 -> Bucket C (LD=2): [(C,1)]\n- 01 -> Bucket D (LD=2): [(B,8), (A,7)]\n- 10 -> Bucket E (LD=2): empty\n- 11 -> Bucket B (LD=2): [(D,4), (D,3)] + overflow [(D,9)]\n\n**Step 8 - Insert (B,5):** Hash(B) = 0101. Prefix \"01\" -> directory 01 -> Bucket D: [(B,8), (A,7)]. Full. Must split.\n- LD(2) = GD(2), so double directory. GD becomes 3. Directory now has 8 entries (000-111).\n- Increment LD to 3. Split Bucket D by bit 3:\n - A(0100) -> prefix 010\n - B(0101) -> prefix 010\n - B(0101) -> prefix 010 (the new record)\n - All three map to prefix 010. Prefix 011 is empty.\n- Directory 010 -> Bucket D (LD=3): Still has A(0100), B(0101), B(0101) = 3 records. Still overflows.\n- LD(3) = GD(3), so double directory again. GD becomes 4. Directory now has 16 entries (0000-1111).\n- Increment LD to 4. Split Bucket D by bit 4:\n - A(0100) -> prefix 0100\n - B(0101) -> prefix 0101\n - B(0101) -> prefix 0101\n - Now separated: A goes to 0100, both B's go to 0101.\n- Directory 0100 -> Bucket F (LD=4): [(A,7)]\n- Directory 0101 -> Bucket D (LD=4): [(B,8), (B,5)]\n\n**Final structure:** GD = 4, 16 directory entries.\n\nDirectory-to-bucket mapping (scanning 0000 to 1111, numbering new buckets in encounter order):\n\n| Directory entries | Bucket | LD | Contents |\n|---|---|---|---|\n| 0000, 0001, 0010, 0011 | Bucket 1 | 2 | [(C,1)] |\n| 0100 | Bucket 2 | 4 | [(A,7)] |\n| 0101 | Bucket 3 | 4 | [(B,8), (B,5)] |\n| 0110, 0111 | Bucket 4 | 3 | empty |\n| 1000, 1001, 1010, 1011 | Bucket 5 | 2 | empty |\n| 1100, 1101, 1110, 1111 | Bucket 6 | 2 | [(D,4), (D,3)] + overflow [(D,9)] |\n\nVerification of directory entry counts per bucket:\n- Bucket 1 (LD=2): $2^{4-2} = 4$ entries. Correct (0000-0011).\n- Bucket 2 (LD=4): $2^{4-4} = 1$ entry. Correct (0100).\n- Bucket 3 (LD=4): $2^{4-4} = 1$ entry. Correct (0101).\n- Bucket 4 (LD=3): $2^{4-3} = 2$ entries. Correct (0110, 0111).\n- Bucket 5 (LD=2): $2^{4-2} = 4$ entries. Correct (1000-1011).\n- Bucket 6 (LD=2): $2^{4-2} = 4$ entries. Correct (1100-1111).\nTotal entries: 4+1+1+2+4+4 = 16. Correct.\n\n$N = 6$ buckets. Total records = 7 (6 in main buckets + 1 in overflow).\n\n---\n\n## Final Computation\n\n$e = \\text{round}(10 \\times 1.000 \\times 0.625 \\times 0.667 \\times 0.833)$\n\n$= \\text{round}(10 \\times 0.34722) = \\text{round}(3.4722) = 3$\n\n$p = ((e-1) \\bmod N) = ((3-1) \\bmod 6) = (2 \\bmod 6) = 2$. Since $p \\neq 0$, bucket $p = 2$.\n$q = ((e+1) \\bmod N) = ((3+1) \\bmod 6) = (4 \\bmod 6) = 4$. Since $q \\neq 0$, bucket $q = 4$.\n\nBucket 2: [(A,7)] = 1 record.\nBucket 4: empty = 0 records.\n\nFraction $= (1 + 0)/7 = 1/7 = 0.14285... \\approx 0.143$.\n\n**Answer:** $a = 1.000$, $b = 0.625$, $c = 0.667$, $d = 0.833$, $e = 3$, final fraction = **0.143**.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given the following tree-path query problem.\n\nA tree has $n$ nodes numbered from $1$ to $n$. Each node $i$ has an integer value $a_i$.\n\nEach query gives two nodes $x$ and $y$. Let the simple path from $x$ to $y$ be\n\n$$x = p_0,\\; p_1,\\; p_2,\\; \\ldots,\\; p_r = y$$\n\nDefine\n\n$$S = \\sum_{k=0}^{r} \\bigl(a_{p_k} \\oplus k\\bigr)$$\n\nwhere $\\oplus$ is bitwise XOR and $k$ is the 0-based position along the path.\n\nThe original input format is:\n\n- First line: integer $t$, the number of test cases.\n- For each test case:\n - First line: integer $n$ with $1 \\le n \\le 5 \\times 10^5$\n - Next $n-1$ lines: edges $u, v$\n - Next line: $n$ integers $a_1, a_2, \\ldots, a_n$ with $0 \\le a_i \\le 10^9$\n - Next line: integer $q$ with $1 \\le q \\le 10^5$\n - Next $q$ lines: queries $x, y$\n\nConstraints:\n\n- The edges form a valid tree.\n- The sum of $n$ over all test cases is at most $5 \\times 10^5$.\n- The sum of $q$ over all test cases is at most $10^5$.\n\nUse this sample instance:\n\n**Sample Input**\n```text\n1\n4\n1 2\n2 3\n3 4\n1 2 3 4\n3\n1 4\n4 1\n2 4\n```\n\n**Sample Output**\n```text\n12\n8\n10\n```\n\nWrite a technical explanation of the solution. Your answer must contain all of the following:\n\n1. A bitwise decomposition of $S$ using symbols $b_k(j)$ for the $j$-th bit of $a_{p_k}$ and $P_j(k)$ for the $j$-th bit of the index $k$, including the per-bit contribution formula.\n2. Definitions of $S_0$, $S_1$, and $C_1$, and the identity\n $$\\sum_{k=0}^{r} (b_k(j) \\oplus P_j(k)) = S_0 + (C_1 - S_1).$$\n3. A closed form for $C_1$ in terms of $r_{\\text{len}} = r+1$, `full_blocks = floor(r_len / 2^{j+1})`, and `rem = r_len mod 2^{j+1}`.\n4. A direct computation for the sample queries showing exactly that $(1,4) \\mapsto 12$, $(4,1) \\mapsto 8$, and $(2,4) \\mapsto 10$.\n5. A bitwise verification of the query $(1,4)$ showing per-bit contributions $4$, $4$, and $4$ for bits $j=0,1,2$.\n6. A naive per-query algorithm that reconstructs the path and scans positions and bits, with time complexity $O(r \\cdot B + \\log n)$ per query.\n7. An optimized method based on binary lifting with per-bit phase counts, with preprocessing complexity $O(n \\cdot \\log n \\cdot B)$ and query complexity $O(B \\cdot \\log n)$.\n", "rubrics": [{"criterion": "Does the answer define b_k(j) as the j-th bit of a_{p_k}, define P_j(k) as the j-th bit of the path index k, and state that the contribution of bit j is 2^j times the sum of b_k(j) XOR P_j(k) over the path positions?", "weight": 15}, {"criterion": "Does the answer define S0, S1, and C1 for a fixed bit j and state the identity sum_k (b_k(j) XOR P_j(k)) = S0 + (C1 - S1)?", "weight": 15}, {"criterion": "Does the answer give the closed form C1 = full_blocks * 2^j + max(0, rem - 2^j), with full_blocks = floor(r_len / 2^{j+1}), rem = r_len mod 2^{j+1}, and r_len = r + 1?", "weight": 15}, {"criterion": "Does the answer directly compute the sample query results (1,4) = 12, (4,1) = 8, and (2,4) = 10?", "weight": 15}, {"criterion": "Does the answer verify the sample query (1,4) by bitwise decomposition with per-bit contributions 4, 4, and 4 for bits j = 0, 1, and 2?", "weight": 10}, {"criterion": "Does the answer describe a naive per-query method that reconstructs the path and scans positions and bits, and state its per-query time complexity as O(r * B + log n)?", "weight": 10}, {"criterion": "Does the answer describe an optimized binary-lifting approach with per-bit phase counts and state preprocessing complexity O(n * log n * B) and query complexity O(B * log n)?", "weight": 20}], "golden_answer": "## Bitwise Decomposition\n\nLet the path for a query be $p_0, p_1, \\ldots, p_r$. For each bit position $j \\ge 0$, define\n\n$$b_k(j) = ((a_{p_k} \\gg j) \\mathbin{\\&} 1)$$\n\nand\n\n$$P_j(k) = ((k \\gg j) \\mathbin{\\&} 1).$$\n\nThen the $j$-th bit of $a_{p_k} \\oplus k$ is\n\n$$b_k(j) \\oplus P_j(k).$$\n\nSo the contribution of bit $j$ to\n\n$$S = \\sum_{k=0}^{r} (a_{p_k} \\oplus k)$$\n\nis\n\n$$2^j \\cdot \\sum_{k=0}^{r} (b_k(j) \\oplus P_j(k)).$$\n\nTherefore,\n\n$$S = \\sum_{j \\ge 0} 2^j \\cdot \\sum_{k=0}^{r} (b_k(j) \\oplus P_j(k)).$$\n\n## Simplifying the Per-Bit Count\n\nFix a bit $j$. Let\n\n- $S_0$ be the sum of $b_k(j)$ over positions with $P_j(k)=0$.\n- $S_1$ be the sum of $b_k(j)$ over positions with $P_j(k)=1$.\n- $C_1$ be the number of positions with $P_j(k)=1$.\n\nThen\n\n$$\\sum_{k=0}^{r} (b_k(j) \\oplus P_j(k)) = S_0 + (C_1 - S_1).$$\n\nReason:\n\n- If $P_j(k)=0$, then $b_k(j) \\oplus P_j(k)=b_k(j)$, so those positions contribute $S_0$.\n- If $P_j(k)=1$, then $b_k(j) \\oplus P_j(k)=1-b_k(j)$, so those positions contribute $C_1-S_1$.\n\nAdding the two parts gives the identity.\n\n## Closed Form for $C_1$\n\nLet\n\n$$r_{\\text{len}} = r+1.$$\n\nFor a fixed bit $j$, the sequence $P_j(k)$ over consecutive indices has period $2^{j+1}$ and looks like\n\n- $2^j$ zeros,\n- then $2^j$ ones.\n\nDefine\n\n$$\\text{full\\_blocks} = \\left\\lfloor \\frac{r_{\\text{len}}}{2^{j+1}} \\right\\rfloor,\\qquad \\text{rem} = r_{\\text{len}} \\bmod 2^{j+1}.$$\n\nEach full block contributes exactly $2^j$ ones, and the remainder contributes $\\max(0, \\text{rem} - 2^j)$ ones. Hence\n\n$$C_1 = \\text{full\\_blocks} \\cdot 2^j + \\max(0, \\text{rem} - 2^j).$$\n\n## Direct Computation on the Sample\n\nThe sample tree is the chain $1-2-3-4$ with values $a=[1,2,3,4]$.\n\nFor query $(1,4)$, the path is $[1,2,3,4]$:\n\n$$S = (1 \\oplus 0) + (2 \\oplus 1) + (3 \\oplus 2) + (4 \\oplus 3) = 1 + 3 + 1 + 7 = 12.$$\n\nFor query $(4,1)$, the path is $[4,3,2,1]$:\n\n$$S = (4 \\oplus 0) + (3 \\oplus 1) + (2 \\oplus 2) + (1 \\oplus 3) = 4 + 2 + 0 + 2 = 8.$$\n\nFor query $(2,4)$, the path is $[2,3,4]$:\n\n$$S = (2 \\oplus 0) + (3 \\oplus 1) + (4 \\oplus 2) = 2 + 2 + 6 = 10.$$\n\nThese are exactly the sample outputs: $12$, $8$, and $10$.\n\n## Bitwise Verification for Query $(1,4)$\n\nHere $r=3$, so the path has four positions $k=0,1,2,3$.\n\nFor $j=0$:\n\n- $P_0(k) = [0,1,0,1]$\n- $b_k(0)$ from values $[1,2,3,4]$ is $[1,0,1,0]$\n- $S_0 = 1+1 = 2$\n- $S_1 = 0+0 = 0$\n- $C_1 = 2$\n\nSo the contribution is\n\n$$2^0 \\cdot (S_0 + C_1 - S_1) = 1 \\cdot (2+2-0) = 4.$$\n\nFor $j=1$:\n\n- $P_1(k) = [0,0,1,1]$\n- $b_k(1) = [0,1,1,0]$\n- $S_0 = 0+1 = 1$\n- $S_1 = 1+0 = 1$\n- $C_1 = 2$\n\nSo the contribution is\n\n$$2^1 \\cdot (1+2-1) = 4.$$\n\nFor $j=2$:\n\n- $P_2(k) = [0,0,0,0]$\n- $b_k(2) = [0,0,0,1]$\n- $S_0 = 1$\n- $S_1 = 0$\n- $C_1 = 0$\n\nSo the contribution is\n\n$$2^2 \\cdot (1+0-0) = 4.$$\n\nThus the per-bit contributions for $j=0,1,2$ are $4$, $4$, and $4$, summing to $12$.\n\n## Naive Per-Query Method\n\nA direct method for one query is:\n\n1. Reconstruct the path from $x$ to $y$ using an LCA-based path decomposition.\n2. Enumerate the path positions $k=0$ to $r$.\n3. For each relevant bit $j$, scan all positions, compute or accumulate the needed values, and add the contribution for that bit.\n\nIf $B$ is the number of relevant bit positions, this costs\n\n$$O(r \\cdot B + \\log n)$$\n\nper query: $O(\\log n)$ to support path reconstruction with LCA machinery and $O(r \\cdot B)$ to scan the path and bits. This is too slow in the worst case because $r$ can be $\\Theta(n)$.\n\n## Optimized Method\n\nUse binary lifting with per-bit phase counts.\n\nFor each node $u$, jump size $2^k$, and bit $j$, store two counts over that upward segment:\n\n- how many nodes with bit $j$ equal to $1$ lie at offsets whose $j$-th offset bit is $0$,\n- how many lie at offsets whose $j$-th offset bit is $1$.\n\nThis lets two adjacent $2^k$ segments be merged in $O(1)$ per bit because the second half is shifted by exactly $2^k$, so for each bit $j$ its phase either stays the same or swaps depending on whether that shift flips the $j$-th offset bit.\n\nDuring a query:\n\n1. Split the path using the LCA.\n2. Decompose each side into $O(\\log n)$ lifted segments.\n3. Maintain the global offset along the full path so each stored segment count is mapped to the correct phase.\n4. Aggregate per-bit counts and then apply the formula above.\n\nThe complexities are:\n\n- preprocessing: $O(n \\cdot \\log n \\cdot B)$\n- per query: $O(B \\cdot \\log n)$\n\nThis meets the given constraints.\n"}
{"domain": "Computer Systems & Operating Systems", "prompt": "A Count-Min Sketch (CMS) is used to estimate frequencies over a stream of integer keys.\n\n-----------------------------------\nSKETCH CONFIGURATION\n-----------------------------------\n\n- Depth: d = 4 rows \n- Width: w = 11 columns \n- Counters are indexed from 0 to 10 \n- All counters are initialized to 0 \n- No pre-warming is applied \n\n-----------------------------------\nHASH FUNCTIONS\n-----------------------------------\n\nFor any non-negative integer x:\n\ng₁(x) = (3x + 2) mod 11 \ng₂(x) = (5x + 7) mod 11 \ng₃(x) = (7x + 1) mod 11 \ng₄(x) = (9x + 4) mod 11 \n\n-----------------------------------\nUPDATE RULE (STANDARD CMS)\n-----------------------------------\n\nFor each update (x, Δ):\n\n- If Δ ≤ 0, ignore the update \n- Otherwise, for each row i = 1..4:\n - Increment counter[i][gᵢ(x)] by Δ \n\n-----------------------------------\nQUERY RULE\n-----------------------------------\n\nTo query key x:\n\n- Compute the 4 counters addressed by g₁(x), g₂(x), g₃(x), g₄(x)\n- Return the minimum of these 4 values \n\n-----------------------------------\nUPDATES (IN ORDER)\n-----------------------------------\n\n(4, 6) \n(9, 3) \n(20, 5) \n(1, 4) \n(31, 2) \n(9, 7) \n(2, -3) \n(13, 1) \n(20, 4) \n(0, 2) \n(9, -2) \n(22, 8) \n(31, 5) \n(20, 1) \n\n-----------------------------------\nTASK\n-----------------------------------\n\nAfter processing all updates, determine the final CMS state relevant to querying key x = 20.\n\nUse row numbers 1 through 4.\n\n-----------------------------------\nOUTPUT FORMAT\n\nOutput exactly the following 7 lines, with no extra text:\n\nignored_updates: <integer>\nhashes_20: <g1>,<g2>,<g3>,<g4>\ncounter_1_7: <integer>\ncounter_2_8: <integer>\ncounter_3_9: <integer>\ncounter_4_8: <integer>\nquery_20: <integer>\n\nFor `hashes_20`, list the four hash results for x = 20 in the order g1, g2, g3, g4, separated by commas and with no spaces.\n", "rubrics": [{"criterion": "The response states `ignored_updates: 2`.", "weight": 5}, {"criterion": "The response states `hashes_20: 7,8,9,8`.", "weight": 15}, {"criterion": "The response states `counter_1_7: 27`.", "weight": 10}, {"criterion": "The response states `counter_2_8: 27`.", "weight": 10}, {"criterion": "The response states `counter_3_9: 27`.", "weight": 10}, {"criterion": "The response states `counter_4_8: 27`.", "weight": 10}, {"criterion": "The response states `query_20: 27`.", "weight": 20}], "golden_answer": "Reasoning\n\nOnly updates with positive delta are applied. Therefore `(2, -3)` and `(9, -2)` are ignored, so the number of ignored updates is 2.\n\nFor the query key `x = 20`, the four hash locations are:\n\n- `g1(20) = (3*20 + 2) mod 11 = 62 mod 11 = 7`\n- `g2(20) = (5*20 + 7) mod 11 = 107 mod 11 = 8`\n- `g3(20) = (7*20 + 1) mod 11 = 141 mod 11 = 9`\n- `g4(20) = (9*20 + 4) mod 11 = 184 mod 11 = 8`\n\nSo `hashes_20 = 7,8,9,8`.\n\nTo determine the final values of those four counters, sum the positive updates from every key that lands in the same bucket in each row.\n\nFor key `20`, the positive updates are `(20,5)`, `(20,4)`, and `(20,1)`, for a total contribution of `10`.\n\nKey `9` hashes to the same four positions:\n\n- `g1(9) = (27 + 2) mod 11 = 29 mod 11 = 7`\n- `g2(9) = (45 + 7) mod 11 = 52 mod 11 = 8`\n- `g3(9) = (63 + 1) mod 11 = 64 mod 11 = 9`\n- `g4(9) = (81 + 4) mod 11 = 85 mod 11 = 8`\n\nIts positive updates are `(9,3)` and `(9,7)`, for a total of `10`.\n\nKey `31` also hashes to the same four positions:\n\n- `g1(31) = (93 + 2) mod 11 = 95 mod 11 = 7`\n- `g2(31) = (155 + 7) mod 11 = 162 mod 11 = 8`\n- `g3(31) = (217 + 1) mod 11 = 218 mod 11 = 9`\n- `g4(31) = (279 + 4) mod 11 = 283 mod 11 = 8`\n\nIts positive updates are `(31,2)` and `(31,5)`, for a total of `7`.\n\nThe remaining keys do not change the queried counters for `x = 20`, because at least one of their row positions differs from the needed counter in each row. Therefore each queried counter receives exactly:\n\n- `10` from key `20`\n- `10` from key `9`\n- `7` from key `31`\n\nThat gives:\n\n- `counter_1_7 = 27`\n- `counter_2_8 = 27`\n- `counter_3_9 = 27`\n- `counter_4_8 = 27`\n\nThe CMS query returns the minimum of these four addressed counters, so:\n\n- `query_20 = min(27, 27, 27, 27) = 27`\n\nRequired final output\n\nignored_updates: 2\nhashes_20: 7,8,9,8\ncounter_1_7: 27\ncounter_2_8: 27\ncounter_3_9: 27\ncounter_4_8: 27\nquery_20: 27\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given a permutation `p` of size `n` (containing each integer from `1` to `n` exactly once).\n\nFor the current permutation, define for each current position `i` (1-indexed):\n\n`c_i = |i - p_i|`\n\nYou may repeatedly remove elements from the current permutation. A removal is valid if the chosen element satisfies `c_i <= s`.\n\nAfter each removal:\n- The remaining elements shift left to fill the gap.\n- The remaining values are relabeled to again form a permutation of `1..k`:\n subtract `1` from every remaining value that was greater than the removed value.\n- Then all `c_i` values are recomputed on the new permutation.\n\nTo remove all ambiguity, if more than one position is currently removable, always remove the leftmost removable position.\n\nGoal: find the minimum integer `s` such that this deterministic process removes the entire permutation.\n\nInput:\n\n`n = 5`\n`p = [3,1,5,2,4]`\n\nRequired output:\n\nOutput exactly these 5 lines and nothing else:\n\n`s=<minimum s>`\n`positions=<comma-separated removed positions>`\n`values=<comma-separated removed values>`\n`states=[3,1,5,2,4]->...->[]`\n`why_s_minus_1_fails=<one sentence>`\n\nUse the deterministic leftmost-removable rule for every step.\n", "rubrics": [{"criterion": "States `s=1` as the minimum integer that allows the deterministic process to remove the entire permutation.", "weight": 20}, {"criterion": "States `positions=2,1,2,1,1` exactly.", "weight": 20}, {"criterion": "States `values=1,2,1,2,1` exactly.", "weight": 15}, {"criterion": "States `states=[3,1,5,2,4]->[2,4,1,3]->[3,1,2]->[2,1]->[1]->[]` exactly.", "weight": 20}, {"criterion": "Explains that `s-1 = 0` fails because the initial permutation has no position with `i = p_i`, so no removal is valid at the start when `c_i` must equal 0.", "weight": 15}, {"criterion": "Uses the exact 5-line output structure requested in the prompt with no extra lines or omitted lines.", "weight": 10}], "golden_answer": "s=1\npositions=2,1,2,1,1\nvalues=1,2,1,2,1\nstates=[3,1,5,2,4]->[2,4,1,3]->[3,1,2]->[2,1]->[1]->[]\nwhy_s_minus_1_fails=s-1=0 fails because the initial permutation [3,1,5,2,4] has no position with i=p_i, so no element has c_i=0 and the process cannot start.\n\nReasoning\n\nThe key detail is that `c_i` must be recomputed after every removal because both positions and values change. The original version treated the initial `c_i` values as if they stayed fixed, which is not correct for this process.\n\nCheck `s = 0` first, because the minimum `s` must be the smallest nonnegative integer that works. With `s = 0`, a move is valid only when `|i - p_i| = 0`, which means `i = p_i`. In the initial permutation `[3,1,5,2,4]`, the position-value pairs are `(1,3)`, `(2,1)`, `(3,5)`, `(4,2)`, `(5,4)`. None of them satisfy `i = p_i`, so there is no valid first move. Therefore `s = 0` is impossible.\n\nNow test `s = 1` using the required deterministic rule: always remove the leftmost currently valid position.\n\nStart with `[3,1,5,2,4]`.\n- Current `c` values are `[2,1,2,2,1]`.\n- Valid positions are 2 and 5, so remove the leftmost one: position 2, value 1.\n- After shifting and relabeling values greater than 1 down by 1, the new permutation is `[2,4,1,3]`.\n\nFor `[2,4,1,3]`:\n- Current `c` values are `[1,2,2,1]`.\n- Valid positions are 1 and 4, so remove the leftmost one: position 1, value 2.\n- After shifting and relabeling values greater than 2 down by 1, the new permutation is `[3,1,2]`.\n\nFor `[3,1,2]`:\n- Current `c` values are `[2,1,1]`.\n- Valid positions are 2 and 3, so remove the leftmost one: position 2, value 1.\n- After shifting and relabeling values greater than 1 down by 1, the new permutation is `[2,1]`.\n\nFor `[2,1]`:\n- Current `c` values are `[1,1]`.\n- Valid positions are 1 and 2, so remove the leftmost one: position 1, value 2.\n- After shifting and relabeling, the new permutation is `[1]`.\n\nFor `[1]`:\n- Current `c` value is `[0]`.\n- Remove position 1, value 1, leaving `[]`.\n\nSo `s = 1` succeeds, and `s = 0` fails. Therefore the minimum valid `s` is `1`.\n"}
{"domain": "Programming Languages, Compilers & Formal Methods", "prompt": "In the secretary problem, an adversary chooses $n$ values $x_1 \\ge x_2 \\ge \\dots \\ge x_n$ in $[0,1]$ that arrive online at independent uniform random times in $[0,1]$. An online algorithm must irrevocably select exactly one value upon seeing it (selecting $0$ if none is chosen). The regret of an algorithm on instance $\\vec{x}$ is $x_1 - \\mathbb{E}[\\text{selected value}]$, and the worst-case regret is its supremum over all $\\vec{x}$.\n\nA pricing-curve algorithm is defined by a measurable threshold function $f:[0,1] \\to [0,1]$ and selects the first arriving value $v$ at time $t$ with $v \\ge f(t)$, or $0$ if none arrives.\n\nProve rigorously that the pricing-curve algorithm with $f(t)=1-t$ has worst-case regret at most $1/4$, and that every pricing-curve algorithm (any $f$) has worst-case regret at least $1/4$. The proofs must be fully self-contained, use only elementary probability, Lebesgue measure, and calculus, and hold for all $n \\ge 1$.", "rubrics": [{"criterion": "Does the proof explicitly consider the harder variant in which $t_1 \\sim U[0,1]$ is random but the adversary chooses all arrival times $t_2, \\dots, t_n$ in advance?", "weight": 10}, {"criterion": "Does the proof remove every $x_i < f(t_i)$ for $i \\ge 2$ and state that this does not change the algorithm’s behavior or regret?", "weight": 10}, {"criterion": "Does the proof define $j = \\arg\\min_{i \\ge 2}$?", "weight": 10}, {"criterion": "Does the proof reduce the instance to keeping only $x_1$ and $x_j$ while preserving behavior and regret?", "weight": 10}, {"criterion": "Does the proof state that the algorithm selects $x_1$ if and only if $t_1 \\in [1-x_1, t_j]$?", "weight": 10}, {"criterion": "Does the proof write the exact regret expression $(x_1 - x_j)(1 - (t_j - (1 - x_1)))$?", "weight": 10}, {"criterion": "Does the proof invoke the inequality $x_j \\ge 1 - t_j$ to bound the regret expression?", "weight": 10}, {"criterion": "Does the proof claim that the quadratic $(a - b)(1 - a + b)$ for $a \\ge b \\in [0,1]$ is at most $1/4$?", "weight": 10}, {"criterion": "Does the lower-bound proof define $\\alpha = \\mu(\\{t \\in [0,1] : f(t) < 0.5\\})$?", "weight": 10}, {"criterion": "Does the lower-bound proof separately handle the case $\\alpha > 1/2$ by arguing that, as $n \\to \\infty$, the algorithm accepts some value by time $0.5$ with probability approaching $1$ when $t_1 \\ge 0.5$?", "weight": 10}, {"criterion": "Does the lower-bound proof correctly handle the $\\alpha \\le 1/2$ case by setting $\\alpha = \\mu(\\{t : f(t) < 0.5\\})$?", "weight": 10}], "golden_answer": "Upper bound ($f(t)=1-t$): Consider the harder variant where $t_1 \\sim U[0,1]$ but $t_2, \\dots, t_n$ are chosen adversarially in advance (any bound here implies the original). Remove every $x_i < f(t_i)$ for $i \\ge 2$ (unchanged behavior). Let $j = \\arg\\min_{i \\ge 2} t_i$ (add $x_2=0$ at $t_2=1$ if needed), then keep only $x_1, x_j$ (unchanged). The algorithm picks $x_1$ iff $t_1 \\in [1-x_1, t_j]$, else $x_j$. Regret equals $(x_1 - x_j)(1 - (t_j - (1 - x_1)))$. Since $x_j \\ge 1 - t_j$, this is at most $(x_1 - x_j)(1 - x_1 + x_j) \\le 1/4$ (maximum of quadratic $(a-b)(1-a+b)$ on $a \\ge b \\in [0,1]$ is $1/4$).\n\nLower bound (any $f$): Let $\\alpha = \\mu(\\{t : f(t) < 0.5\\})$.\n * If $\\alpha \\le 1/2$, take $n=1$, $x_1=0.5$: expected value $\\le \\alpha \\cdot 0.5 \\le 0.25$, regret $\\ge 0.25$.\n * If $\\alpha > 1/2$, take $x_1=1$, $x_i=0.5$ for $i \\ge 2$. With probability $1/2$, $t_1 \\ge 0.5$. Also $\\mu(\\{t \\in [0, 0.5] : f(t) \\ge 0.5\\}) \\ge \\alpha - 1/2 > 0$. As $n \\to \\infty$, probability of accepting some value by time $0.5$ approaches $1$. Thus regret approaches at least $0.5(1 - 0.5) = 0.25$.\n\nIn both cases worst-case regret $\\ge 1/4$."}
{"domain": "Algorithms & Data Structures", "prompt": "## Problem\n\nShivam is playing a game with his friends Varad (who controls the doll) and Tanmay.\n\nThere are `n` boxes in a line, numbered `1..n`. Varad hides a doll in one box. Shivam will make `m` guesses: on the `i`-th guess Shivam asks whether the doll is currently in box `a[i]`.\n\nVarad can “cheat” by moving the doll **before the first guess** and also **after every guess**:\n- she may move the doll to a neighboring box (`i -> i-1` or `i -> i+1`) or keep it in place,\n- moves must stay within `1..n`.\n\nSo the order is:\n- game starts (doll at start box `x`),\n- Varad makes one move,\n- Shivam guesses `a1`,\n- Varad moves,\n- Shivam guesses `a2`,\n- ...\n- Shivam guesses `am`,\n- Varad moves,\n- game ends (doll at end box `y`).\n\nShivam **loses** (i.e., Varad wins) if **none** of Shivam’s guesses ever equals the doll’s position at that moment.\n\nYou are given `n`, `m`, and the guess sequence `a1..am`. \nCount the number of pairs `(x, y)` with `1 ≤ x, y ≤ n` such that Varad can choose moves so that:\n- the doll starts at `x`,\n- Shivam never guesses correctly,\n- the doll ends at `y`.\n\n### Input\n- First line: `n m` (`1 ≤ n, m ≤ 1e5`)\n- Second line: `m` integers `a1..am` (`1 ≤ ai ≤ n`)\n\n### Output\nPrint the number of winning scenarios `(x,y)`.\n", "rubrics": [{"criterion": "The answer states that for each fixed start box x, the set of reachable end boxes y forms a consecutive segment [L[x], R[x]] (except trivial n=1 handling).", "weight": 10}, {"criterion": "The answer states that the final count is computed as the sum over x of the segment lengths (e.g., sum max(0, R[x]-L[x]+1)).", "weight": 10}, {"criterion": "The answer describes computing L[x] and R[x] as extreme reachable ends using a greedy strategy (always push left for L, always push right for R).", "weight": 10}, {"criterion": "The answer states that the right-bound computation is obtained by a symmetric/mirrored procedure of the left-bound computation.", "weight": 10}, {"criterion": "The answer uses a DSU (union-find) idea to merge starting positions whose greedy simulation leads to the same current box, so their future evolution is identical.", "weight": 10}, {"criterion": "The answer specifies that at guess i, any simulated state that equals the forbidden box a[i] must be shifted to an alternative position to avoid losing immediately (e.g., forced move to a[i]+1 for the left-bound sweep).", "weight": 10}, {"criterion": "The answer includes boundary handling for moves at boxes 1 and n (cannot move to 0 or n+1).", "weight": 10}, {"criterion": "The answer explicitly describes that after processing guess i, the greedy-left sweep applies a move curPos := max(1, curPos−1) (or an equivalent uniform “try move left” update).", "weight": 10}, {"criterion": "The answer states that when two DSU components move into the same current box during the sweep, they are unioned/merged.", "weight": 10}, {"criterion": "The answer states an overall time complexity of O((n+m) α(n)) or O(n+m) (near-linear) for computing all bounds.", "weight": 10}], "golden_answer": "### 1) Model as reachable positions with “forbidden” points at guess times\n\nLet the doll’s position **before** guess `i` be `pos[i]` (so `pos[1]` is after Varad’s initial move).\nConstraints:\n- `pos[i] != a[i]` for all `i = 1..m` (otherwise Shivam guesses correctly).\n- `pos[i+1]` is obtained from `pos[i]` by a move in `{ -1, 0, +1 }` staying in `[1..n]`.\n- The final position after the last extra move is `y = pos[m+1]`.\n\nFor a fixed start `x`, the set of reachable end positions `y` (over Varad’s choices) is always a **consecutive segment** `[L[x], R[x]]` (for `n=1` it is trivial). Intuition: the movement graph is 1D and “holes” created by forbidding a single point at a time get filled again by the ±1 closure; reachability remains interval-like.\n\nTherefore the required answer is:\n\\[\n\\sum_{x=1}^{n} \\max(0, R[x]-L[x]+1).\n\\]\n\nSo we only need to compute, for every start `x`, the **leftmost** possible end `L[x]` and the **rightmost** possible end `R[x]`.\n\n---\n\n### 2) Compute extreme ends via greedy, but for all starts simultaneously\n\nTo get `L[x]` (leftmost possible end), consider an optimal strategy that always tries to move the doll as far **left** as possible, only deviating when that would place it on the next forbidden guess box. Symmetrically, `R[x]` is obtained by always trying to move as far **right** as possible.\n\nDoing this independently for each `x` would be `O(nm)`, too slow. The key is that many starting points quickly become indistinguishable under the greedy process: once two starts lead to the same current position under the greedy policy, their future behavior (and thus final bound) is identical. We can merge such starts.\n\n---\n\n### 3) DSU “merge-starts-by-current-cell” sweep for the left bound\n\nWe process guesses from `i=1` to `m` and maintain groups of starting positions whose greedy-simulated doll position (just before guess `i`) is the same cell.\n\nData structure:\n- A disjoint set union over starting indices `x=1..n`.\n- For each DSU component, we store the current simulated position `curPos(comp)` (a box number).\n- We also maintain for each box `v` which DSU component currently sits at `v` (if any), so if two components move into the same `v`, we union them.\n\nUpdate rule per step `i` for left-bound simulation:\n1. **Avoid the forbidden box.** \n If some component currently has `curPos = a[i]`, then to keep losing, it must shift to the smallest possible alternative, i.e. to the right neighbor `a[i]+1` if it exists, otherwise the component becomes impossible (no valid path for those starts).\n2. **Apply Varad’s move after guess `i` to prepare for the next step.** \n Greedy-left move: every component tries to move `curPos := max(1, curPos-1)`.\n\nWhenever step (1) or (2) moves a component into a box already occupied by another component, we union them (because from this point on, their greedy evolution is identical).\n\nAt the end (after processing guess `m` and then the final move), the value `curPos` of the component containing start `x` equals `L[x]`.\n\nBoundary handling:\n- Moves that would go to `0` stay at `1`.\n- If step (1) requires moving from `n` to `n+1`, that component is marked “dead” (contributes 0 end positions).\n\nThis sweep is near-linear because each union happens at most `n-1` times and each component changes position only when forced by a guess or by the uniform greedy shift.\n\nCompute `R[x]` with the symmetric sweep (mirror the line):\n- replace each guess `a[i]` by `a'[i] = n+1-a[i]`,\n- compute left bounds `L'` on the mirrored instance,\n- map back: `R[x] = n+1 - L'[n+1-x]`.\n\n---\n\n### 4) Final counting\n\nAfter obtaining arrays `L[1..n]` and `R[1..n]` (with “dead” starts contributing 0),\nsum:\n\\[\n\\text{ans} = \\sum_{x=1}^n \\max(0, R[x]-L[x]+1).\n\\]\n\n---\n\n### 5) Complexity\n\nBoth sweeps are `O((n+m) α(n))` with DSU (effectively linear for constraints), and memory is `O(n+m)`.\n"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given an undirected tree with `n` vertices numbered `1` to `n`. Vertex `i` has an integer value `a_i`.\n\nYou may perform the following operation any number of times:\n\n- Choose a vertex with current degree `≤ 1` and delete it (and its incident edge if it exists).\n\nYou may delete all vertices.\n\nAfter deletions, perform **compression**:\n\n- While there exists a vertex of degree exactly `2`, delete it and connect its two neighbors by an edge.\n\nRepeat until no degree-2 vertices remain. The final compressed tree is unique (order-independent).\n\nCompute the maximum possible **sum of values of vertices remaining after compression**.\n\n### Input\n- `n` (`2 ≤ n ≤ 5·10^5`)\n- `a_1, ..., a_n` (`-10^9 ≤ a_i ≤ 10^9`)\n- `n-1` undirected edges `u v` forming a tree\n\n### Output\nOne integer: the maximum achievable sum.", "rubrics": [{"criterion": "Does the answer explicitly state: in the chosen remaining subtree S (before compression), a vertex contributes a_v to the final sum iff deg_S(v) ≠ 2 (and contributes 0 iff deg_S(v)=2 because it is removed during compression)?", "weight": 20}, {"criterion": "Does the answer formally define dp1[v] as the maximum obtainable final sum using only vertices in subtree(v) under the condition that the edge (parent(v),v) is kept in the remaining subtree S?", "weight": 10}, {"criterion": "Does the answer state the dp1[v] candidate for keeping 0 child edges as a_v (degree in S equals 1, so v is not compressed)?", "weight": 10}, {"criterion": "Does the answer state the dp1[v] candidate for keeping exactly 1 child edge as max_u dp1[u] and explicitly exclude adding a_v (degree in S equals 2, so v is compressed)?", "weight": 10}, {"criterion": "Does the answer state the dp1[v] candidate for keeping ≥2 child edges as a_v + bestSum_{≥2}?", "weight": 10}, {"criterion": "Does the answer define the component (no-parent-edge) candidate for keeping 0 child edges as a_v (degree 0, v remains)?", "weight": 10}, {"criterion": "Does the answer define the component candidate for keeping exactly 1 child edge as a_v + best1 (degree 1, v remains)?", "weight": 10}, {"criterion": "Does the answer define the component candidate for keeping exactly 2 child edges as best2 and explicitly exclude adding a_v (degree 2, v is compressed)?", "weight": 10}, {"criterion": "Does the answer state the final output is max(0, maximum over all vertices of the component candidates) to allow deleting all vertices?", "weight": 10}], "golden_answer": "## Expert Solution\n\nRoot the tree at node `1`. Any sequence of leaf deletions leaves a connected subtree `S` (possibly empty).\n\n#### Key characterization (compression effect)\nCompression repeatedly deletes every vertex of degree exactly `2`. It never deletes vertices of degree `0`, `1`, or `≥ 3`. Hence:\n\n**A vertex `v` contributes `a_v` to the final sum iff `deg_S(v) ≠ 2`;**\n**if `deg_S(v) = 2` then `v` is removed and contributes `0`.**\n\n---\n\n## DP definition\nLet `parent(v)` and `children(v)` be w.r.t. the rooting.\n\n`dp1[v] = maximum final (post-compression) sum using only subtree(v)`\n**under the condition that** edge `(parent(v), v)` is kept in `S`.\n\nThen `v` has a parent-edge, so:\n`deg_S(v) = 1 + #{kept child edges (v, u)}`\n\nFor each child `u`, either keep `(v, u)` (gain `dp1[u]`) or delete that child side (gain `0`).\nLet `b_u = dp1[u]` for children `u`.\n\n---\n\n## Deterministic helper values from `{b_u}`\n- `best1 = max(b_u)` (requires `≥ 1` child)\n- `best2 =` sum of the two largest `b_u` (requires `≥ 2` children)\n- `bestSum_{≥k}` for `k ∈ {2, 3}`: maximum sum over any subset of children of size `≥ k`\n\nCompute `bestSum_{≥k}` deterministically:\nLet `P = ∑_{u: b_u > 0} b_u`, and `p = #{u: b_u > 0}`.\n- If `p ≥ k`: `bestSum_{≥k} = P`\n- Else: `bestSum_{≥k} = P +` (sum of the `k - p` largest values among the non-positive `b_u`).\n\nThis is optimal: take all positive contributions, then add the least harmful remaining values until reaching size `k`.\n\n---\n\n## Transition for `dp1[v]`\nLet `k` be the number of kept child edges.\n\n1) `k = 0`: `deg_S(v) = 1 ⇒ v` is **not compressed**, so include `a_v`:\n `cand0 = a_v`\n\n2) `k = 1`: `deg_S(v) = 2 ⇒ v` **is compressed**, so **exclude `a_v`**:\n `cand1 = best1`\n\n3) `k ≥ 2`: `deg_S(v) ≥ 3 ⇒ v` is **not compressed**, so include `a_v`:\n `candGe2 = a_v + bestSum_{≥2}`\n\nTherefore:\n`dp1[v] = max(cand0, cand1 (if exists), candGe2 (if exists))`\n\n---\n\n## Component candidates (no parent edge)\nA remaining subtree `S` can be entirely inside `subtree(v)` without keeping the parent edge. Then `deg_S(v)` equals the number of kept child edges, giving four explicit cases:\n\n- keep 0 children: `deg = 0 ⇒ v` remains\n `val0 = a_v`\n- keep 1 child: `deg = 1 ⇒ v` remains\n `val1 = a_v + best1`\n- keep 2 children: `deg = 2 ⇒ v` is compressed (**exclude `a_v`**)\n `val2 = best2`\n- keep `≥ 3` children: `deg ≥ 3 ⇒ v` remains\n `valGe3 = a_v + bestSum_{≥3}`\n\nLet `ans` be the maximum of these component candidates over all vertices `v`.\n\nFinally, deleting all vertices is allowed, so the output is:\n`max(0, ans)`\n\nCompute `dp1[v]` in postorder and update `ans` at each vertex. Use 64-bit integers."}
{"domain": "Computer Systems & Operating Systems", "prompt": "This problem tests knowledge of operating systems and CPU scheduling. A system implements Multilevel Feedback Queue (MLFQ) scheduling with I/O handling and priority boosting.\n\nSYSTEM CONFIGURATION:\n- 3 queues: Q0 (highest priority), Q1 (medium), Q2 (lowest)\n- Time quantum: Q0=2ms, Q1=4ms, Q2=8ms\n- Higher-priority queues preempt lower-priority queues (see Rule 8); within the same queue, round-robin applies (see Rule 6)\n- 5 processes: P1, P2, P3, P4, P5\n\nSCHEDULING RULES (apply exactly as stated):\n\nRULE 1 (Priority): Always run the highest-priority (lowest queue number) ready process. Q0 > Q1 > Q2.\n\nRULE 2 (New Process): New processes enter at Q0 with a full Q0 quantum.\n\nRULE 3 (Quantum Exhaustion): If a process uses its entire time quantum without its CPU burst completing, demote it to the next lower queue (Q0->Q1->Q2). Q2 processes stay in Q2. Demotion applies even if the quantum boundary coincides with a preemption event. If a CPU burst completes at the exact same instant as the quantum expires, the burst completion takes precedence: the process is NOT demoted; it either blocks for I/O (Rule 4) or finishes, whichever applies next.\n\nRULE 4 (I/O Block): If a process blocks for I/O before its quantum expires, it stays in its current queue. Its remaining quantum is discarded.\n\nRULE 5 (I/O Completion): When I/O completes, the process returns to the BACK of its current queue with a fresh full quantum for that queue.\n\nRULE 6 (Round Robin): Within the same queue, use round-robin. The process at the front runs first.\n\nRULE 7 (Priority Boost): Every 20ms (at t=20, t=40, t=60, ...), ALL processes in the system are moved to Q0, including processes currently blocked on I/O. After the boost, the Q0 order is by ascending process ID (P1 before P2, etc.). Each process receives a fresh Q0 quantum.\n\nRULE 8 (Preemption): A newly ready higher-priority (lower queue number) process immediately preempts the running process. The preempted process goes to the BACK of its current queue with its remaining quantum preserved.\n\nRULE 9 (Tie-Breaking): If multiple processes enter the same queue at the exact same instant (e.g., after a priority boost or simultaneous I/O completions), they are ordered within that queue by ascending process ID (P1 before P2, etc.). Processes already in a queue before the simultaneous event retain their existing relative order; the newly arrived processes are appended after them in ascending PID order.\n\nRULE 10 (I/O Duration): I/O takes exactly the specified duration. A process cannot use the CPU during I/O.\n\nRULE 11 (Simultaneous Events): When multiple events occur at the same time, process them in this order: (1) I/O completion, (2) new process arrival, (3) quantum expiry or CPU burst completion, (4) priority boost.\n\nRULE 12 (CPU Idle): The CPU idles only if all arrived and not-yet-finished processes are blocked on I/O.\n\nINITIAL STATE (time 0):\nAll queues empty. CPU idle.\n\nPROCESS ARRIVALS AND BEHAVIOR:\nP1: Arrives t=0, CPU burst pattern: 3ms, I/O 5ms, 4ms, I/O 3ms, 6ms, DONE\nP2: Arrives t=1, CPU burst pattern: 5ms, I/O 4ms, 2ms, I/O 6ms, 3ms, DONE\nP3: Arrives t=3, CPU burst pattern: 7ms, I/O 2ms, 5ms, DONE\nP4: Arrives t=6, CPU burst pattern: 2ms, I/O 8ms, 4ms, I/O 2ms, 1ms, DONE\nP5: Arrives t=10, CPU burst pattern: 9ms, I/O 3ms, 2ms, DONE\n\n(Pattern: CPU burst, then I/O, then CPU burst, etc., until DONE)\n\nCOMPUTE EXACTLY THESE TEN VALUES:\n(1) V1: At what time does P1 complete (all bursts finished)?\n(2) V2: The total time the CPU is idle (no process running).\n(3) V3: How many queue demotions occur during the entire execution? (A demotion is a move from a higher queue to a lower queue caused by quantum exhaustion, not by a priority boost.)\n(4) V4: At time t=25, which process is currently running? \"At time t=25\" means the state at exactly t=25ms, after all simultaneous events at t=25 have been resolved per Rule 11. Report the process ID (1-5), or 0 if the CPU is idle.\n(5) V5: How many priority boosts (Rule 7) actually move at least one process from a non-Q0 queue (or from I/O-blocked state in a non-Q0 queue) to Q0?\n(6) V6: The product of the completion times of P2 and P4.\n(7) V7: How many context switches occur? Count each time the CPU switches from one process to another, or from idle to a process. Do not count a running process blocking for I/O or completing as a separate context switch; count only the subsequent transition when the CPU picks up the next process.\n(8) V8: The total time P3 spends in the READY state (in a queue, not running and not blocked on I/O).\n(9) V9: At time t=40, after the priority boost has been applied, how many processes are in Q2?\n(10) V10: Verification checksum: U = (V1 + V3 * V5 + V7) mod 79.\n\nFORMAT: V1=<int>;V2=<int>;V3=<int>;V4=<int>;V5=<int>;V6=<int>;V7=<int>;V8=<int>;V9=<int>;V10=<int>", "rubrics": [{"criterion": "Does the answer state that V1 (P1 completion time) equals exactly 49?", "weight": 15}, {"criterion": "Does the answer state that V2 (total CPU idle time) equals exactly 3?", "weight": 5}, {"criterion": "Does the answer state that V3 (total queue demotions) equals exactly 12?", "weight": 15}, {"criterion": "Does the answer state that V4 (process running at t=25) equals exactly 5?", "weight": 5}, {"criterion": "Does the answer state that V5 (priority boosts that moved at least one process) equals exactly 2?", "weight": 5}, {"criterion": "Does the answer state that V6 (product of P2 and P4 completion times) equals exactly 1376?", "weight": 15}, {"criterion": "Does the answer state that V7 (context switches) equals exactly 27?", "weight": 15}, {"criterion": "Does the answer state that V8 (total time P3 spends in the ready state) equals exactly 23?", "weight": 15}, {"criterion": "Does the answer state that V9 (number of processes in Q2 at t=40 after boost) equals exactly 0?", "weight": 5}, {"criterion": "Does the answer state that V10 (verification checksum) equals exactly 21?", "weight": 5}], "golden_answer": "## Setup\n\nQueues: Q0 (quantum=2ms, highest), Q1 (quantum=4ms), Q2 (quantum=8ms, lowest).\nPriority boost fires at t=20, t=40, ...\nAll processes including I/O-blocked ones are moved to Q0 on a boost (Rule 7).\nDemotion occurs on full quantum exhaustion, even when that coincides with a preemption (Rule 3).\nOn I/O completion, a process gets a fresh quantum for its current queue (Rule 5).\n\n\n---\n\n## Detailed Execution Timeline\n\n### Phase 1: t=0 to t=20 (before first boost)\n\nt=0: P1 arrives -> Q0. CPU idle -> P1 starts. Q0=[P1 running].\nt=0-2: P1 runs 2ms (full Q0 quantum). burst_rem=1ms. P1 demoted -> Q1.\n DEMOTION 1: P1 Q0->Q1.\n\nt=1: P2 arrives -> Q0 back. (P1 still running until t=2; no preemption, same queue.)\n\nt=2: P1's quantum expires -> P1->Q1 (burst_rem=1ms). Q0=[P2]. P2 starts.\n CONTEXT SWITCH 1: (idle->P1 at t=0) [initial start]\n CONTEXT SWITCH 2: P1->P2 at t=2.\n\nt=2-4: P2 runs 2ms (full Q0 quantum). burst_rem=3ms. P2 demoted -> Q1.\n DEMOTION 2: P2 Q0->Q1.\n\nt=3: P3 arrives -> Q0 back. (P2 running; no preemption.)\n\nt=4: P2's quantum expires -> P2->Q1 (burst_rem=3ms). Q0=[P3]. P3 starts.\n CONTEXT SWITCH 3: P2->P3 at t=4.\n\nt=4-6: P3 runs 2ms (full Q0 quantum). burst_rem=5ms.\n\nt=6: P4 arrives (Rule 11 step 2: arrival before quantum expiry).\n P4 -> Q0. Then P3's quantum expires (Rule 11 step 3) -> P3 demoted Q0->Q1 (burst_rem=5ms).\n DEMOTION 3: P3 Q0->Q1.\n Q0=[P4]. P4 starts.\n CONTEXT SWITCH 4: P3->P4 at t=6.\n\nt=6-8: P4 runs 2ms. P4's CPU burst is exactly 2ms = full Q0 quantum.\n P4's burst completes at t=8. P4 blocks for I/O (8ms, done at t=16). Rule 4: P4 stays Q0.\n\nt=8: P4 blocks -> I/O. Q0=[] (P4 blocked). Q1=[P1(burst_rem=1), P2(burst_rem=3), P3(burst_rem=5)].\n P1 (front of Q1) starts. Fresh Q1 quantum=4ms.\n CONTEXT SWITCH 5: P4->P1 at t=8.\n\nt=8-9: P1 runs 1ms, completes burst 1. P1 blocks for I/O (5ms, done at t=14). Stays Q1.\n Q1=[P2, P3].\n CONTEXT SWITCH 6: P1->P2 at t=9.\n\nt=9: P2 starts in Q1. burst_rem=3ms, quantum=4ms.\n\nt=10: P5 arrives -> Q0. P5 (Q0) preempts P2 (Q1) per Rule 8.\n P2 back of Q1 with quantum_rem=3ms, burst_rem=2ms.\n Q0=[P5]. Q1=[P3, P2].\n CONTEXT SWITCH 7: P2->P5 at t=10.\n\nt=10-12: P5 runs 2ms (full Q0 quantum). P5 demoted -> Q1 (burst_rem=7ms).\n DEMOTION 4: P5 Q0->Q1.\n\nt=12: P5->Q1 (back). Q1=[P3, P2, P5]. P3 starts. Fresh quantum=4ms.\n CONTEXT SWITCH 8: P5->P3 at t=12.\n\nt=12-16: P3 runs 4ms (full Q1 quantum). burst_rem=1ms. Normally demoted Q1->Q2.\n At t=16: P4 I/O done (Rule 11: I/O before quantum expiry).\n P4 I/O completes -> P4 back of Q0. P4 (Q0) preempts P3 (Q1).\n P3 has used its full Q1 quantum -> per Rule 3, P3 is demoted Q1->Q2 (burst_rem=1ms).\n DEMOTION 5: P3 Q1->Q2.\n CONTEXT SWITCH 9: P3->P4 at t=16.\n\nt=14: P1 I/O done -> P1 back of Q1. Q1=[P2, P5, P1]. (P3 still running at that point.)\n\nt=16-18: P4 runs 2ms (full Q0 quantum). burst_rem=2ms. P4 demoted -> Q1.\n DEMOTION 6: P4 Q0->Q1.\n\nt=18: P4->Q1 (back). Q1=[P2, P5, P1, P4]. P2 starts. quantum_rem=3ms (preserved), burst_rem=2ms.\n CONTEXT SWITCH 10: P4->P2 at t=18.\n\nt=18-20: P2 runs 2ms, completing burst 1 at exactly t=20.\n\n### Phase 2: Priority Boost at t=20\n\nAt t=20, per Rule 11:\n Step 1: P2 completes burst, blocks for I/O (4ms, done at t=24). P2 stays Q1 (Rule 4).\n Step 2: Priority boost fires.\n - P1 (Q1, ready) -> Q0.\n - P2 (Q1, I/O-blocked, non-Q0) -> Q0 (boost includes I/O-blocked, Rule 7).\n - P3 (Q2, ready) -> Q0.\n - P4 (Q1, ready) -> Q0.\n - P5 (Q1, ready) -> Q0.\n Q0=[P1, P2(blocked), P3, P4, P5] ordered by PID. Each gets fresh Q0 quantum=2ms.\nBOOST 1 moves processes: YES. EFFECTIVE BOOST COUNT = 1.\n CPU: P1 (front of Q0, lowest PID among ready) starts.\n CONTEXT SWITCH 11: P2->P1 at t=20.\n\nt=20-22: P1 runs 2ms (full Q0 quantum). burst_rem=2ms. P1 demoted -> Q1.\n DEMOTION 7: P1 Q0->Q1.\n\nt=22: Q0=[P3, P4, P5]. P3 starts.\n CONTEXT SWITCH 12: P1->P3 at t=22.\n\nt=22-23: P3 runs 1ms, completing burst 1 at t=23. P3 blocks I/O (2ms, done at t=25). Stays Q0.\n CONTEXT SWITCH 13: P3->P4 at t=23.\n\nt=23-25: P4 runs. burst_rem=2ms, quantum=2ms. P4's burst done at t=25 = quantum boundary.\n P4 blocks for I/O (2ms, done at t=27). Stays Q0.\n\nt=24: P2 I/O done -> P2 back of Q0. Q0=[P5, P2] (P4 still running).\n\nt=25: Per Rule 11: I/O before quantum expiry.\n P3 I/O done at t=25 -> P3 back of Q0. Q0=[P5, P2, P3].\n P4 burst done (at quantum boundary) -> P4 blocks I/O (done at t=27). Stays Q0.\n CPU: P5 starts.\n CONTEXT SWITCH 14: P4->P5 at t=25.\n\n V4 = 5 (P5 starts running at t=25).\n\nt=25-27: P5 runs 2ms (full Q0 quantum). burst_rem=5ms. P5 demoted -> Q1.\n DEMOTION 8: P5 Q0->Q1.\n\nt=27: Per Rule 11: I/O before quantum expiry.\n P4 I/O done -> P4 back of Q0.\n P5 quantum expires -> P5 demoted Q0->Q1.\n Q0=[P2, P3, P4]. P2 starts.\n CONTEXT SWITCH 15: P5->P2 at t=27.\n\nt=27-29: P2 runs 2ms (burst 2 = 2ms = full quantum). P2 burst done, blocks I/O (6ms, done at t=35). Stays Q0.\n\nt=29: Q0=[P3, P4]. P3 starts.\n CONTEXT SWITCH 16: P2->P3 at t=29.\n\nt=29-31: P3 runs 2ms (full Q0 quantum). burst_rem=3ms. P3 demoted -> Q1.\n DEMOTION 9: P3 Q0->Q1.\n\nt=31: Q0=[P4]. P4 starts.\n CONTEXT SWITCH 17: P3->P4 at t=31.\n\nt=31-32: P4 runs 1ms, completing burst 3 (1ms < quantum=2ms). P4 DONE at t=32.\n P4 completion = t=32.\n CONTEXT SWITCH 18: P4->P1 at t=32.\n\nt=32: Q0=[]. Q1=[P1(burst_rem=2ms), P5(burst_rem=5ms), P3(burst_rem=3ms)]. P1 starts.\n\nt=32-34: P1 runs 2ms, completing burst 2 at t=34. P1 blocks I/O (3ms, done at t=37). Stays Q1.\n CONTEXT SWITCH 19: P1->P5 at t=34.\n\nt=34-35: P5 runs 1ms in Q1.\n\nt=35: P2 I/O done -> P2 back of Q0. P2 (Q0) preempts P5 (Q1).\n P5 back of Q1: quantum_rem=3ms, burst_rem=4ms.\n Q0=[P2]. Q1=[P3, P5].\n CONTEXT SWITCH 20: P5->P2 at t=35.\n\nt=35-37: P2 runs 2ms in Q0 (burst 3 = 3ms, quantum=2ms). Quantum expires at t=37. burst_rem=1ms.\n P2 demoted Q0->Q1.\n DEMOTION 10: P2 Q0->Q1.\n\nt=37: Per Rule 11: P1 I/O done first -> P1 back of Q1. Then P2 quantum expires -> P2 Q1 (back).\n Q1=[P3, P5, P1, P2]. P3 starts.\n CONTEXT SWITCH 21: P2->P3 at t=37.\n\nt=37-40: P3 runs 3ms, completing burst 2 at t=40. P3 DONE at t=40.\n P3 completion = t=40.\n\n### Phase 3: Priority Boost at t=40\n\nAt t=40, per Rule 11:\n Step 1: P3 burst complete -> P3 exits (done).\n Step 2: Priority boost fires.\n Remaining processes: P1 (Q1), P2 (Q1), P5 (Q1).\n All moved to Q0. Q0=[P1, P2, P5] (by PID). Fresh Q0 quantum=2ms.\nBOOST 2 moves processes: YES. EFFECTIVE BOOST COUNT = 2.\n CONTEXT SWITCH 22: P3->P1 at t=40.\n\nV5 = 2 (both boosts moved at least one process).\n\nV9 = 0 (Q2 is empty after boost at t=40 -- all processes moved to Q0).\n\nt=40-42: P1 runs 2ms (full Q0 quantum). burst_rem=4ms. P1 demoted -> Q1.\n DEMOTION 11: P1 Q0->Q1.\n\nt=42: Q0=[P2, P5]. P2 starts.\n CONTEXT SWITCH 23: P1->P2 at t=42.\n\nt=42-43: P2 runs 1ms, completing burst 3. P2 DONE at t=43.\n P2 completion = t=43.\n CONTEXT SWITCH 24: P2->P5 at t=43.\n\nt=43-45: P5 runs 2ms (full Q0 quantum). burst_rem=2ms. P5 demoted -> Q1.\n DEMOTION 12: P5 Q0->Q1.\n\nt=45: Q1=[P1(burst_rem=4ms), P5(burst_rem=2ms)]. P1 starts.\n CONTEXT SWITCH 25: P5->P1 at t=45.\n\nt=45-49: P1 runs 4ms in Q1 (burst=4ms, quantum=4ms). P1 burst done at t=49. P1 DONE.\n P1 completion = t=49.\n CONTEXT SWITCH 26: P1->P5 at t=49.\n\nt=49-51: P5 runs 2ms in Q1, completing burst 1 (total 9ms across all slices). P5 blocks I/O (3ms, done at t=54). Stays Q1.\n\nt=51-54: CPU IDLE. Only P5 remains and is blocked on I/O.\n IDLE DURATION = 3ms.\n CONTEXT SWITCH 27: idle->P5 at t=54.\n\nt=54-56: P5 runs 2ms in Q1, completing burst 2. P5 DONE at t=56.\n\n---\n\n## Summary of Values\n\nV1 = 49 (P1 completion time)\n\nV2 = 3 (CPU idle: t=51 to t=54, 3ms)\n\nV3 = 12 (demotions)\n P1: Q0->Q1 (t=2)\n P2: Q0->Q1 (t=4)\n P3: Q0->Q1 (t=6)\n P5: Q0->Q1 (t=12)\n P3: Q1->Q2 (t=16, quantum exhausted even though preemption was simultaneous per Rule 3)\n P4: Q0->Q1 (t=18)\n P1: Q0->Q1 (t=22, after boost)\n P5: Q0->Q1 (t=27)\n P3: Q0->Q1 (t=31)\n P2: Q0->Q1 (t=37)\n P1: Q0->Q1 (t=42, after boost)\n P5: Q0->Q1 (t=45)\n\nV4 = 5 (P5 starts running at t=25)\n\nV5 = 2 (boost at t=20 and boost at t=40 each moved processes)\n\nV6 = 43 * 32 = 1376 (P2 completes t=43, P4 completes t=32)\n\nV7 = 27 (context switches: 25 process-to-process transitions\n + 2 idle-to-process transitions: idle->P1 at t=0, idle->P5 at t=54.\n Transitions from process to idle, e.g. at t=51, are not counted.)\n\nV8 = 23 (P3 ready time)\n t=3-4: 1ms (Q0, P2 running)\n t=6-12: 6ms (Q1, P4 then P1 then P2 then P5 running)\n t=16-20: 4ms (Q2, P4 then P2 running)\n t=20-22: 2ms (Q0, P1 running after boost)\n t=25-29: 4ms (Q0, P5 then P2 running)\n t=31-37: 6ms (Q1, P4 completes then P1 then P5 preempted then P2)\n Total: 1+6+4+2+4+6 = 23ms\n\nV9 = 0 (at t=40, after boost, Q0=[P1,P2,P5], Q1=[], Q2=[])\n\nV10 = (V1 + V3*V5 + V7) mod 79\n = (49 + 12*2 + 27) mod 79\n = (49 + 24 + 27) mod 79\n = 100 mod 79\n = 21\n\n---\n\n## Final Answer\n\nV1=49;V2=3;V3=12;V4=5;V5=2;V6=1376;V7=27;V8=23;V9=0;V10=21"}
{"domain": "Programming Languages, Compilers & Formal Methods", "prompt": "Simulate Tomasulo's Algorithm with speculative execution for the following instruction sequence.\n\nCONFIGURATION:\nFunctional Units: 2 Add/Sub (2 cycles), 1 Mul (4 cycles), 1 Div (8 cycles), 1 Load (3 cycles).\nReservation Stations: 3 Add (Add1, Add2, Add3), 2 Mul (Mul1, Mul2), 2 Load (Load1, Load2).\nReorder Buffer: 8 entries (ROB1-ROB8).\nCommon Data Bus: 1 (only one result broadcast per cycle, priority: Add1 < Add2 < Add3 < Mul1 < Mul2 < Load1 < Load2).\n\nRules:\n(1) Issue: One instruction issues per cycle in program order if RS and ROB available.\n(2) Execute: Begins cycle after ALL operands ready (not same cycle operand broadcasts).\n(3) Write Result: Broadcasts on CDB one cycle after execution completes.\n(4) Commit: In-order from ROB after write completes.\n(5) Structural Hazards: Stall issue if no RS or ROB entry available.\n(6) RAW Hazards: Wait for operand via CDB broadcast.\n\nREGISTER FILE (initial values):\nF0=1.0, F2=2.0, F4=4.0, F6=6.0, F8=8.0, F10=10.0\n\nINSTRUCTION SEQUENCE (I1-I12):\nI1: LOAD F2, 0(R1) ; F2 = Mem[R1+0]\nI2: LOAD F4, 0(R2) ; F4 = Mem[R2+0]\nI3: MUL F6, F2, F4 ; F6 = F2 * F4\nI4: ADD F8, F6, F2 ; F8 = F6 + F2\nI5: DIV F10, F8, F4 ; F10 = F8 / F4\nI6: SUB F2, F6, F4 ; F2 = F6 - F4\nI7: ADD F4, F2, F8 ; F4 = F2 + F8\nI8: MUL F0, F4, F6 ; F0 = F4 * F6\nI9: LOAD F12, 0(R3) ; F12 = Mem[R3+0]\nI10: ADD F14, F12, F0 ; F14 = F12 + F0\nI11: SUB F16, F14, F10 ; F16 = F14 - F10\nI12: MUL F18, F16, F6 ; F18 = F16 * F6\n\nTrack each instruction through: Issue (I), Execute Start (X), Execute End (E), Write Result (W), Commit (C).\n\nCompute the following EXACT values:\n\n(1) In which cycle does I3 begin execution?\n(2) In which cycle does I5 write its result to CDB?\n(3) What is the SUM of issue cycles for all 12 instructions?\n(4) How many cycles have at least one instruction in execution phase?\n(5) In which cycle does I8 begin execution?\n(6) What is the PRODUCT of cycles where I1, I2, and I3 write results?\n(7) How many total stall cycles occur due to structural hazards?\n(8) What is the cycle number when I12 commits?\n(9) At cycle 10, how many reservation stations are occupied?\n(10) What is the ratio of ADD/SUB operations to MUL operations expressed as A:B in lowest terms?", "rubrics": [{"criterion": "Does the answer state that I3 begins execution in exactly cycle 7?", "weight": 10}, {"criterion": "Does the answer state that I5 writes its result in exactly cycle 23?", "weight": 10}, {"criterion": "Does the answer state that the sum of issue cycles for all 12 instructions is exactly 108?", "weight": 10}, {"criterion": "Does the answer state that exactly 26 cycles have at least one instruction executing?", "weight": 10}, {"criterion": "Does the answer state that I8 begins execution in exactly cycle 19?", "weight": 10}, {"criterion": "Does the answer state that the product of write cycles for I1, I2, and I3 is exactly 330?", "weight": 10}, {"criterion": "Does the answer state that exactly 7 stall cycles occur due to structural hazards?", "weight": 10}, {"criterion": "Does the answer state that I12 commits in exactly cycle 36?", "weight": 10}, {"criterion": "Does the answer state that exactly 5 reservation stations are occupied at cycle 10?", "weight": 10}, {"criterion": "Does the answer state that the ratio of ADD/SUB to MUL operations is exactly 5:3?", "weight": 10}], "golden_answer": "TOMASULO'S ALGORITHM EXECUTION TRACE\n\n=== CYCLE-BY-CYCLE EXECUTION ===\n\nCYCLE 1:\n- I1 (LOAD F2) ISSUES to Load1, ROB1\n- Load1: Busy, Op=Load, Dest=ROB1\n- ROB1: Busy, Instr=I1, Dest=F2, Ready=No\n\nCYCLE 2:\n- I1 begins EXECUTION (cycles 2-4, 3 cycles for Load)\n- I2 (LOAD F4) ISSUES to Load2, ROB2\n- Load2: Busy, Op=Load, Dest=ROB2\n\nCYCLE 3:\n- I1 executing (cycle 2 of 3)\n- I2 begins EXECUTION (cycles 3-5)\n- I3 (MUL F6, F2, F4) ISSUES to Mul1, ROB3\n- Mul1: waiting for F2 (ROB1), F4 (ROB2)\n\nCYCLE 4:\n- I1 execution ENDS\n- I2 executing (cycle 2 of 3)\n- I3 waiting for operands\n- I4 (ADD F8, F6, F2) ISSUES to Add1, ROB4\n- Add1: waiting for F6 (ROB3), F2 (ROB1)\n\nCYCLE 5:\n- I1 WRITES to CDB (F2 ready) - Load1 freed\n- I2 execution ENDS\n- I3 captures F2, still waiting for F4\n- I4 captures F2, still waiting for F6\n- I5 (DIV F10, F8, F4) ISSUES to Mul2, ROB5\n- Mul2: waiting for F8 (ROB4), F4 (ROB2)\n\nCYCLE 6:\n- I1 COMMITS (ROB1 freed)\n- I2 WRITES to CDB (F4 ready) - Load2 freed\n- I3 captures F4 (all operands ready, executes NEXT cycle)\n- I5 captures F4, still waiting for F8\n- I6 (SUB F2, F6, F4) ISSUES to Add2, ROB6\n- Add2: waiting for F6 (ROB3), has F4\n\nCYCLE 7:\n- I2 COMMITS (ROB2 freed)\n- I3 begins EXECUTION (cycles 7-10, 4 cycles for MUL)\n- I6 waiting for F6\n- I7 (ADD F4, F2, F8) ISSUES to Add3, ROB7\n- Add3: waiting for F2 (ROB6), F8 (ROB4)\n\nCYCLE 8:\n- I3 executing (cycle 2 of 4)\n- I8 (MUL F0, F4, F6) ISSUES to Mul1 (freed after I3 writes), ROB8\n- Wait - Mul1 still busy with I3!\n- I8 STALLS (no Mul RS available)\n\nCYCLE 9:\n- I3 executing (cycle 3 of 4)\n- I8 STALLS (structural hazard - Mul1, Mul2 both busy)\n\nCYCLE 10:\n- I3 execution ENDS\n- I8 STALLS\n\nCYCLE 11:\n- I3 WRITES to CDB (F6 ready) - Mul1 freed\n- I4 captures F6 (all operands ready)\n- I6 captures F6 (all operands ready)\n- I8 (MUL F0, F4, F6) ISSUES to Mul1, ROB8\n- Mul1: waiting for F4 (ROB7), has F6\n\nCYCLE 12:\n- I3 COMMITS (ROB3 freed)\n- I4 begins EXECUTION (cycles 12-13, 2 cycles for ADD)\n- I6 begins EXECUTION (cycles 12-13, 2 cycles for SUB)\n- I8 waiting for F4\n- I9 (LOAD F12) ISSUES to Load1, ROB1 (reused)\n\nCYCLE 13:\n- I4 execution ENDS\n- I6 execution ENDS\n- I9 begins EXECUTION (cycles 13-15)\n\nCYCLE 14:\n- I4 WRITES to CDB (F8 ready) - Add1 freed (priority)\n- I5 captures F8 (all operands ready)\n- I7 captures F8, still waiting for F2\n- CDB conflict: I6 must wait\n\nCYCLE 15:\n- I4 COMMITS (ROB4 freed)\n- I6 WRITES to CDB (F2 ready) - Add2 freed\n- I7 captures F2 (all operands ready)\n- I8 waiting for F4 (from I7)\n- I5 begins EXECUTION (cycles 15-22, 8 cycles for DIV)\n- I9 execution ENDS\n\nCYCLE 16:\n- I5 executing (cycle 2 of 8)\n- I9 WRITES to CDB (F12 ready) - Load1 freed\n- I7 begins EXECUTION (cycles 16-17)\n- I10 (ADD F14, F12, F0) ISSUES to Add1, ROB2\n- Add1: has F12, waiting for F0 (ROB8)\n\nCYCLE 17:\n- I5 executing\n- I7 execution ENDS\n- I6 COMMITS (ROB6 freed)\n\nCYCLE 18:\n- I5 executing\n- I7 WRITES to CDB (F4 ready) - Add3 freed\n- I8 captures F4 (all operands ready)\n- I11 (SUB F16, F14, F10) ISSUES to Add2, ROB6\n- Add2: waiting for F14 (ROB2), F10 (ROB5)\n\nCYCLE 19:\n- I5 executing\n- I7 COMMITS (ROB7 freed)\n- I8 begins EXECUTION (cycles 19-22, 4 cycles for MUL)\n- I12 (MUL F18, F16, F6) ISSUES to Mul2 - Wait, Mul2 has I5!\n- I12 STALLS (no Mul RS)\n\nCYCLE 20:\n- I5 executing\n- I8 executing\n- I12 STALLS\n\nCYCLE 21:\n- I5 executing\n- I8 executing\n- I12 STALLS\n\nCYCLE 22:\n- I5 execution ENDS\n- I8 execution ENDS\n- I12 STALLS\n\nCYCLE 23:\n- I5 WRITES to CDB (F10 ready) - Mul2 freed (priority over I8)\n- I11 captures F10, waiting for F14\n- I8 must wait for CDB\n- I12 ISSUES to Mul2, ROB7\n- Mul2: waiting for F16 (ROB6), has F6\n\nCYCLE 24:\n- I5 COMMITS (ROB5 freed)\n- I8 WRITES to CDB (F0 ready) - Mul1 freed\n- I10 captures F0 (all operands ready)\n- I12 waiting for F16\n\nCYCLE 25:\n- I8 COMMITS (ROB8 freed)\n- I10 begins EXECUTION (cycles 25-26)\n- I9 COMMITS (ROB1 freed)\n\nCYCLE 26:\n- I10 execution ENDS\n\nCYCLE 27:\n- I10 WRITES to CDB (F14 ready) - Add1 freed\n- I11 captures F14 (all operands ready)\n\nCYCLE 28:\n- I10 COMMITS (ROB2 freed)\n- I11 begins EXECUTION (cycles 28-29)\n\nCYCLE 29:\n- I11 execution ENDS\n\nCYCLE 30:\n- I11 WRITES to CDB (F16 ready) - Add2 freed\n- I12 captures F16 (all operands ready)\n\nCYCLE 31:\n- I11 COMMITS (ROB6 freed)\n- I12 begins EXECUTION (cycles 31-34)\n\nCYCLE 32-34:\n- I12 executing\n\nCYCLE 35:\n- I12 WRITES to CDB (F18 ready)\n\nCYCLE 36:\n- I12 COMMITS (ROB7 freed)\n- EXECUTION COMPLETE\n\n=== INSTRUCTION TIMING SUMMARY ===\n\nInst | Issue | ExecStart | ExecEnd | Write | Commit\n-----|-------|-----------|---------|-------|-------\nI1 | 1 | 2 | 4 | 5 | 6\nI2 | 2 | 3 | 5 | 6 | 7\nI3 | 3 | 7 | 10 | 11 | 12\nI4 | 4 | 12 | 13 | 14 | 15\nI5 | 5 | 15 | 22 | 23 | 24\nI6 | 6 | 12 | 13 | 15 | 17\nI7 | 7 | 16 | 17 | 18 | 19\nI8 | 11 | 19 | 22 | 24 | 25\nI9 | 12 | 13 | 15 | 16 | 25\nI10 | 16 | 25 | 26 | 27 | 28\nI11 | 18 | 28 | 29 | 30 | 31\nI12 | 23 | 31 | 34 | 35 | 36\n\n=== ANSWER CALCULATIONS ===\n\n(1) Cycle I3 begins execution: 7\n\n(2) Cycle I5 writes result: 23\n\n(3) Sum of issue cycles:\n1+2+3+4+5+6+7+11+12+16+18+23 = 108\n\n(4) Cycles with at least one instruction executing:\nCycles 2,3,4,5,7,8,9,10,12,13,14,15,16,17,19,20,21,22,25,26,28,29,31,32,33,34 = 26 cycles\n\n(5) Cycle I8 begins execution: 19\n\n(6) Product of write cycles for I1, I2, I3:\n5 × 6 × 11 = 330\n\n(7) Stall cycles due to structural hazards:\nI8 stalls cycles 8,9,10 (3 cycles)\nI12 stalls cycles 19,20,21,22 (4 cycles)\nTotal: 7 stall cycles\n\n(8) Cycle I12 commits: 36\n\n(9) Reservation stations occupied at cycle 10:\nMul1 (I3), Mul2 (I5), Add1 (I4), Add2 (I6), Add3 (I7) = 5 stations\n\n(10) Ratio ADD/SUB to MUL:\nADD/SUB: I4, I6, I7, I10, I11 = 5 operations\nMUL: I3, I8, I12 = 3 operations\nRatio = 5:3\n\n=== FINAL ANSWERS ===\n\n(1) 7\n(2) 23\n(3) 108\n(4) 26\n(5) 19\n(6) 330\n(7) 7\n(8) 36\n(9) 5\n(10) 5:3"}
{"domain": "Algorithms & Data Structures", "prompt": "You are given a multiset `a` of size `n`: `a_1, a_2, ..., a_n`.\n\nYou generate a new multiset `s` as follows:\n\n1. Partition `a` into any number of **non-empty** multisets `x_1, x_2, ..., x_k`, using every element exactly once.\n2. For each `x_i`, choose **one of its modes** and insert it into `s`.\n\nA **mode** of a multiset is any element with maximum frequency in that multiset (ties allowed).\n\nCount how many **different multisets** `s` can be produced (multiplicities matter), modulo `998244353`.\n\n### Input\n- `n` (`1 ≤ n ≤ 5000`)\n- `a_1, ..., a_n` (`1 ≤ a_i ≤ n`)\n\n### Output\nOutput the number of obtainable multisets `s` modulo `998244353`.", "rubrics": [{"criterion": "Does the answer define cnt[v] as the frequency of value v in the input multiset a?", "weight": 10}, {"criterion": "Does the answer state the feasibility condition for a chosen support T (values appearing at least once in s) as: for every x ∉ T, cnt[x] ≤ sum_{c∈T}?", "weight": 10}, {"criterion": "Does the answer simplify feasibility to the single inequality sum_{c∈T}?", "weight": 10}, {"criterion": "Does the answer state that for any feasible support T, the multiplicity of each c∈T in output multiset s can be any integer t_c with 1 ≤ t_c ≤ cnt[c], giving exactly cnt[c] choices per c?", "weight": 10}, {"criterion": "Does the answer define a knapsack DP dp[sum] that equals the total number of outputs whose chosen support has total weight sum = sum_{c∈T}?", "weight": 10}, {"criterion": "Does the answer give the per-color DP transition: dp_next[s] += dp[s] (exclude), and dp_next[s+cnt] += dp[s] * cnt (include), all modulo 998244353?", "weight": 10}, {"criterion": "Does the answer compute the final result as ans = sum_{s = M..n}?", "weight": 10}, {"criterion": "Does the answer explicitly state the modulus as 998244353 and apply it to DP and final answer?", "weight": 10}, {"criterion": "Does the answer state the overall time complexity as O(n^2) and space complexity as O(n) (or O(n^2) if explicitly chosen), consistent with n ≤ 5000?", "weight": 20}], "golden_answer": "### Expert Solution\n\nLet `cnt[v]` be the frequency of value `v` in the input multiset `a`, and let\n`M = max_v cnt[v]`\nAlso let `MOD = 998244353`.\n\n---\n\n## 1) Feasibility condition\n\nLet `T` be the **support** of the output multiset `s` (the set of values that appear at least once in `s`).\n\nFor any value `x ∉ T`, we must be able to place all `cnt[x]` copies of `x` into parts whose **chosen mode** is some `c ∈ T`, without making `x` the *unique* most frequent element in any part.\n\nIf a part’s chosen mode is `c`, then that part can contain at most as many `x`'s as it contains `c`'s (otherwise `x` would be strictly more frequent and thus the unique mode). Summing over all parts whose chosen mode lies in `T`, the total \"hiding capacity\" for `x` is at most `∑_{c ∈ T} cnt[c]`. Hence a necessary condition is:\n`cnt[x] ≤ ∑_{c ∈ T} cnt[c]` for every `x ∉ T`.\n\nThis condition is also sufficient (we can distribute occurrences of each excluded `x` across the mode-parts so that in every part, `#x ≤ #(mode)`).\n\nSince `cnt[x] ≤ M` for all `x`, this is equivalent to the single inequality:\n`∑_{c ∈ T} cnt[c] ≥ M`\n\n---\n\n## 2) Counting multiplicities of `s` for a fixed support\n\nIf `c ∈ T`, then `c` must be chosen as a mode for some positive number `t_c` of parts.\nEach such part must contain at least one `c`, so\n`1 ≤ t_c ≤ cnt[c]`\nThus for each `c ∈ T` there are exactly `cnt[c]` choices for `t_c`, and for fixed support `T` the number of different multisets `s` is:\n`∏_{c ∈ T} cnt[c]`\n\nSo the required answer is:\n`∑_{T: ∑ cnt[c] ≥ M} ( ∏_{c ∈ T} cnt[c] ) (mod MOD)`\n\n---\n\n## 3) Knapsack DP\n\nLet `dp[S]` be the total contribution (sum of products `∏ cnt[c]`) over supports `T` whose total weight\n`S = ∑_{c ∈ T} cnt[c]`\nequals `S`.\n\nInitialize `dp[0] = 1`. For each value `v` with `cnt = cnt[v] > 0`:\n- Exclude `v`: `dp_next[s] += dp[s]`\n- Include `v`: `dp_next[s + cnt] += dp[s] · cnt`\n\nAll updates are modulo `998244353`.\n\nFinally,\n`ans = ∑_{s=M..n} dp[s] (mod 998244353)`\n\n---\n\n## 4) Complexity\n\nThe DP runs over sums `0...n` for at most `n` distinct values, so:\n- Time: `O(n^2)`\n- Memory: `O(n)`\n\nThis fits for `n ≤ 5000`."}
{"domain": "Algorithms & Data Structures", "prompt": "Ashwini is trapped in a nightmare where Gauss appears and challenges her with a task.\n\nRam, her friend, explains the rule:\n\nFor a given integer **n**, Ashwini must produce a sequence **[a₁, a₂, ..., aₙ]** such that:\n\n1. Each **aᵢ** is between **1** and **10¹⁸**. \n2. For every adjacent pair **(aᵢ, aᵢ₊₁)**, the **GCD values must all be distinct**. \n3. The sequence must use the **minimum possible number of distinct elements**.\n\nTo make the task deterministic, Ram adds a strict rule:\n\n> “Ashwini must use the **fixed construction** described below, and output the **lexicographically smallest valid sequence** generated by that construction.”\n\n### Fixed Construction (Deterministic)\n\n1. Let **M = 10**.\n2. Construct **100 distinct integers** using:\n\n \\[\n x_{i,j} = 2^{i} \\cdot 3^{j} \\cdot 5^{9-i} \\cdot 7^{9-j}\n \\quad \\text{for } 0 \\le i, j < 10\n \\]\n\n3. This gives a fixed set **X** of size 100.\n4. Build a complete graph on X, labeling each edge between **xₐ and x_b** with **gcd(xₐ, x_b)**.\n5. Construct an **Eulerian trail** on this graph using **Hierholzer’s algorithm** with a fixed deterministic edge order (sorted by gcd value).\n6. The resulting Eulerian trail produces a deterministic sequence of length **5050** (≥ 5000).\n7. Output the **first n elements** of this Eulerian trail.\n\n### Input format:\n- First line contains **t**, the number of test cases. \n- Each test case contains a single integer **n**.\n\n### Output format:\n- For each test case, output **n** space-separated integers on a new line.\n\nAshwini must solve the nightmare to wake up. She knows a solution always exists.\n\n### Constraints:\n- **1 ≤ t ≤ 200** \n- **2 ≤ n ≤ 5000**\n", "rubrics": [{"criterion": "Does the answer state the final minimum number of distinct elements as k = 100?", "weight": 10}, {"criterion": "Does the answer explicitly give the maximum sequence length formula for odd k as k(k+1)/2 via Euler tour?", "weight": 10}, {"criterion": "Does the answer explicitly give the maximum sequence length formula for even k as k^2/2 + 1?", "weight": 10}, {"criterion": "Does the answer explicitly show the inequality k^2/2 + 1 ≥ 5000 ⇒ k ≥ 100?", "weight": 10}, {"criterion": "Does the answer explicitly define the construction formula x_{i,j}?", "weight": 10}, {"criterion": "Does the answer explicitly set M = 10 for the construction?", "weight": 10}, {"criterion": "Does the answer explicitly state the gcd formula using min-exponents for any two vertices?", "weight": 10}, {"criterion": "Does the answer explicitly claim that the gcd mapping is unique for each unordered pair?", "weight": 20}, {"criterion": "Does the answer specify deterministic Hierholzer traversal rule: choose unused edge with smallest gcd label, tie-break by smallest neighbor index?", "weight": 10}], "golden_answer": "Step 1: Minimum distinct elements (k)\n\nFor a set of k distinct numbers, define a complete graph with k vertices and edges labeled by gcd of endpoints.\nEach adjacent pair in the sequence corresponds to traversing one edge, and all gcds must be distinct ⇒ no edge may be repeated.\n\n- If k is odd, the complete graph has all even degrees ⇒ Euler tour exists covering all edges:\n length = k(k+1)/2\n- If k is even, all degrees are odd. We must delete a matching of size (k−2)/2 to make degrees even, leaving:\n length = k(k+1)/2 − (k−2)/2 = k^2/2 + 1\n\nTo reach n up to 5000, we need:\nk^2/2 + 1 ≥ 5000 ⇒ k ≥ 100\n\nSo **minimum k = 100**.\n\nStep 2: Deterministic set construction\n\nLet M = 10. For 0 ≤ i, j < 10:\n\nx_{i,j} = 2^i * 3^j * 5^(9−i) * 7^(9−j)\n\nThis produces 100 distinct numbers, all ≤ 10^18 (max value = 5^9 * 7^9 = 7.88×10^13).\n\nExample values:\n- x_{0,0} = 2^0 * 3^0 * 5^9 * 7^9 = 78815638671875\n- x_{9,9} = 2^9 * 3^9 * 5^0 * 7^0 = 10077696\n- x_{1,0} = 2^1 * 3^0 * 5^8 * 7^9 = 31526255468750\n- x_{8,9} = 2^8 * 3^9 * 5^1 * 7^0 = 62985600\n- x_{9,8} = 2^9 * 3^8 * 5^0 * 7^1 = 23514624\n\nStep 3: Unique gcd property\n\nFor any two vertices (i1,j1) and (i2,j2), gcd is:\n\n2^{min(i1,i2)} * 3^{min(j1,j2)} * 5^{min(9−i1,9−i2)} * 7^{min(9−j1,9−j2)}\n\nThis mapping is unique for each unordered pair (i1,j1),(i2,j2), so all edge labels are distinct.\n\nStep 4: Eulerian trail (deterministic)\n\nThe graph is Eulerian (all degrees even).\nUse Hierholzer’s algorithm with deterministic edge choice:\n\n- At each vertex, choose the unused edge with **smallest gcd label** (sorted order).\n- If ties occur, choose the smallest neighbor index.\n\nThis produces a deterministic Euler trail of length 5050 edges (5051 vertices).\n\nStep 5: First few elements of the Euler trail (actual computed values)\n\nUsing the deterministic Hierholzer’s traversal, the first vertices in the Euler trail are:\n\nIndex | Value\n----- | -----\n1 | 78815638671875\n2 | 10077696\n3 | 31526255468750\n4 | 25194240\n5 | 78815638671875\n6 | 23514624\n7 | 31526255468750\n8 | 62985600\n9 | 78815638671875\n10 | 58786560\n\nGCDs between consecutive values:\n\n- gcd(78815638671875, 10077696) = 1\n- gcd(10077696, 31526255468750) = 2\n- gcd(31526255468750, 25194240) = 10\n- gcd(25194240, 78815638671875) = 5\n- gcd(78815638671875, 23514624) = 7\n- gcd(23514624, 31526255468750) = 14\n- gcd(31526255468750, 62985600) = 50\n- gcd(62985600, 78815638671875) = 25\n- gcd(78815638671875, 58786560) = 35\n\nAll GCDs are distinct, satisfying the condition.\n\nStep 6: Output\n\nFor each test case n, output the first n vertices from this deterministic Euler trail.\n\nExample outputs:\n\nFor n = 2:\n78815638671875 10077696\n\nFor n = 3:\n78815638671875 10077696 31526255468750\n\nFor n = 5:\n78815638671875 10077696 31526255468750 25194240 78815638671875\n\nVerification:\n- All values ≤ 10^18.\n- Adjacent gcds are distinct.\n- Uses exactly 100 distinct elements (minimum).\n- Deterministic due to fixed construction + fixed traversal.\n"}
{"domain": "Computer Systems & Operating Systems", "prompt": "You are given a distributed system with 4 processes: P0, P1, P2, P3.\n\nEach process maintains a vector clock of size 4.\nAll clocks are initially: [0,0,0,0]\n\n-----------------------------------\nVECTOR CLOCK RULES\n-----------------------------------\n\n1. Internal event:\n Increment own component.\n\n2. Send event:\n Increment own component and send the updated clock.\n\n3. Receive event:\n Take component-wise max of local and received clock,\n then increment own component.\n\n-----------------------------------\nEVENT SEQUENCE\n-----------------------------------\n\nE1: P0 internal \nE2: P1 internal \nE3: P0 sends M1 to P2 \nE4: P2 receives M1 from P0 \nE5: P1 sends M2 to P3 \nE6: P3 receives M2 from P1 \nE7: P2 sends M3 to P1 \nE8: P3 internal \nE9: P1 receives M3 from P2 \nE10: P0 sends M4 to P3 \nE11: P2 internal \nE12: P3 receives M4 from P0 \nE13: P1 sends M5 to P0 \nE14: P0 receives M5 from P1 \nE15: P3 sends M6 to P2 \nE16: P2 receives M6 from P3 \n\n-----------------------------------\nTASK\n-----------------------------------\n\nCompute vector clocks and answer the following:\n\n1. Vector clock at E4 \n2. Vector clock at E9 \n3. Vector clock at E12 \n4. Vector clock at E14 \n5. Vector clock at E16 \n6. Total number of happened-before (→) pairs among all unordered event pairs {Ei, Ej} with i < j. Count a pair if the vector clock of one event is strictly less than the other component-wise. \n7. Total number of concurrent (||) pairs among the same 120 unordered event pairs. Two events are concurrent if neither vector clock is strictly less than the other component-wise. \n8. Event with maximum vector clock sum \n9. Length of the longest causal chain, defined as the maximum number of distinct events in a sequence X1 → X2 → ... → Xk, where each adjacent pair satisfies happened-before. \n10. Number of receive events where exactly 2 components increase when comparing the receiver's local clock immediately before the receive with its clock immediately after applying the receive rule \n\n-----------------------------------\nFINAL OUTPUT FORMAT\n\nE4,E9,E12,E14,E16,HB,CONC,MAX_EVENT,CHAIN_LEN,RECV2\n\nWhere:\n- Each vector clock is formatted as [a,b,c,d]\n- MAX_EVENT is event label (e.g., E16)\n", "rubrics": [{"criterion": "Correctly computes E4 = [2,0,1,0]", "weight": 10}, {"criterion": "Correctly computes E9 = [2,3,2,0]", "weight": 10}, {"criterion": "Correctly computes E12 = [3,2,0,3]", "weight": 10}, {"criterion": "Correctly computes E14 = [4,4,2,0]", "weight": 10}, {"criterion": "Correctly computes E16 = [3,2,4,4]", "weight": 10}, {"criterion": "Correctly computes the number of happened-before pairs among the 120 unordered event pairs as 67", "weight": 10}, {"criterion": "Correctly computes the number of concurrent pairs among the 120 unordered event pairs as 53", "weight": 10}, {"criterion": "Correctly identifies E16 as max sum event", "weight": 10}, {"criterion": "Correctly computes the longest causal chain length as 7 events", "weight": 10}, {"criterion": "Correctly computes that 3 receive events have exactly 2 component increases from the receiver's pre-receive clock to its post-receive clock", "weight": 10}], "golden_answer": "[2,0,1,0],[2,3,2,0],[3,2,0,3],[4,4,2,0],[3,2,4,4],67,53,E16,7,3\n\nEXPLANATION\n\nApply the vector clock rules in order. The complete clock after each event is:\n\n- E1 (P0 internal): [1,0,0,0]\n- E2 (P1 internal): [0,1,0,0]\n- E3 (P0 sends M1 to P2): [2,0,0,0]\n- E4 (P2 receives M1): max([0,0,0,0],[2,0,0,0]) = [2,0,0,0], then increment P2 -> [2,0,1,0]\n- E5 (P1 sends M2 to P3): [0,2,0,0]\n- E6 (P3 receives M2): max([0,0,0,0],[0,2,0,0]) = [0,2,0,0], then increment P3 -> [0,2,0,1]\n- E7 (P2 sends M3 to P1): [2,0,2,0]\n- E8 (P3 internal): [0,2,0,2]\n- E9 (P1 receives M3): max([0,2,0,0],[2,0,2,0]) = [2,2,2,0], then increment P1 -> [2,3,2,0]\n- E10 (P0 sends M4 to P3): [3,0,0,0]\n- E11 (P2 internal): [2,0,3,0]\n- E12 (P3 receives M4): max([0,2,0,2],[3,0,0,0]) = [3,2,0,2], then increment P3 -> [3,2,0,3]\n- E13 (P1 sends M5 to P0): [2,4,2,0]\n- E14 (P0 receives M5): max([3,0,0,0],[2,4,2,0]) = [3,4,2,0], then increment P0 -> [4,4,2,0]\n- E15 (P3 sends M6 to P2): [3,2,0,4]\n- E16 (P2 receives M6): max([2,0,3,0],[3,2,0,4]) = [3,2,3,4], then increment P2 -> [3,2,4,4]\n\nFrom this table:\n\n1. E4 = [2,0,1,0]\n2. E9 = [2,3,2,0]\n3. E12 = [3,2,0,3]\n4. E14 = [4,4,2,0]\n5. E16 = [3,2,4,4]\n\nFor happened-before and concurrency, compare all unordered pairs of events using vector clock comparison. There are C(16,2) = 120 unordered pairs total.\n\n- A pair is happened-before if one vector is strictly less than the other component-wise.\n- A pair is concurrent if neither vector is strictly less than the other.\n\nCounting all 120 pairs gives:\n\n- Happened-before pairs = 67\n- Concurrent pairs = 53\n\nThe event with maximum vector clock sum is E16 because:\n\n- sum(E14) = 4 + 4 + 2 + 0 = 10\n- sum(E15) = 3 + 2 + 0 + 4 = 9\n- sum(E16) = 3 + 2 + 4 + 4 = 13\n\nNo earlier event has a sum greater than 13, so MAX_EVENT = E16.\n\nFor the longest causal chain, one maximum-length sequence is:\n\nE1 -> E3 -> E4 -> E7 -> E9 -> E13 -> E14\n\nEach event in this sequence happened-before the next one, so the chain length is 7 events. No longer chain exists.\n\nFor receive events with exactly 2 component increases, compare the receiver's local clock immediately before and immediately after each receive:\n\n- E4: [0,0,0,0] -> [2,0,1,0], increases in components 0 and 2 only\n- E6: [0,0,0,0] -> [0,2,0,1], increases in components 1 and 3 only\n- E9: [0,2,0,0] -> [2,3,2,0], 3 components increase\n- E12: [0,2,0,2] -> [3,2,0,3], increases in components 0 and 3 only\n- E14: [3,0,0,0] -> [4,4,2,0], 3 components increase\n- E16: [2,0,3,0] -> [3,2,4,4], 4 components increase\n\nSo exactly 3 receive events satisfy the condition: E4, E6, and E12.\n\nFINAL ANSWER\n\n[2,0,1,0],[2,3,2,0],[3,2,0,3],[4,4,2,0],[3,2,4,4],67,53,E16,7,3\n"}