---
id: 1710
lang: en
translation_of: index.md
source_sha256: dd9c22c34d68b3ffb879f2d9e25284ef66afb7dfd1df13cc69d26fec74c3c5c7
title: "[Miscellaneous Problems] - September 21, 2019"
description: "Short notes on seven problems: tree DP, merge sort, DSU on chains, an insertion DP, a backward DP, prefix/suffix DSU and pseudotree diameters."
tags: ["OI","DP","Merge Sort","Disjoint-Set Union","Divide and Conquer","Ad Hoc","Tree DP","Miscellaneous Problems"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "基环数 in the IOI 2008 Island section is a typo for 基环树 (pseudotree) and is translated as “pseudotree”."
  - "The 不等数列 section defines dp[i][j] but then speaks of k less-than signs; the mismatch is kept as written."
---

kal0rona is getting more and more <span class="slang" data-zh="sb" data-gloss="Initials of 傻逼 (shǎbī). A vulgar insult, roughly “idiot” or “stupid”.">stupid</span>.

<!--more-->

## Restaurant

A typical tree DP, and in the exam I <span class="slang" data-zh="特么" data-gloss="tème, a euphemistic spelling of 他妈 (tāmā), “his mother”. A mild curse, like “damn” or “freaking”.">damn</span> went and deleted one of the cases while I was writing it.

Consider the state $dp[i][j][0/1]$: $i$ is the node index, $j$ is the units of time used, $0$ means not necessarily returning to the root, and $1$ means definitely returning to the root. Roughly simulate it and you will know how to transition.

```cpp
// dostavljac.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 550;

int head[MAX_N], current, n, m, ai[MAX_N];
ll dp[MAX_N][MAX_N][2];

struct edge
{
    int to, nxt;
} edges[MAX_N << 1];

void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}

void dfs(int u, int fa)
{
    dp[u][1][0] = dp[u][1][1] = ai[u];
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
        {
            dfs(edges[i].to, u);
            for (int k = m; k >= 0; k--)
            {
                for (int j = m - k; j >= 0; j--)
                {
                    if (j >= 1)
                        dp[u][j + k][0] = max(dp[u][j + k][0], dp[edges[i].to][j - 1][0] + dp[u][k][1]);
                    if (j >= 2)
                        dp[u][j + k][1] = max(dp[u][j + k][1], dp[edges[i].to][j - 2][1] + dp[u][k][1]);
                    if (j >= 2)
                        dp[u][j + k][0] = max(dp[u][j + k][0], dp[edges[i].to][j - 2][1] + dp[u][k][0]);
                }
            }
        }
}

int main()
{
    /*
    freopen("dostavljac.in", "r", stdin);
    freopen("dostavljac.out", "w", stdout);
    */
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &ai[i]);
    for (int i = 1, u, v; i <= n - 1; i++)
        scanf("%d%d", &u, &v), addpath(u, v), addpath(v, u);
    dfs(1, 0);
    printf("%lld", max(dp[1][m][1], dp[1][m][0]));
    return 0;
}
```

## Random

My approach to this problem is a bit different: I did not use Two-Pointers + Multiset.

I noticed: for a pair $(a_i, a_j)$ that might contribute to the answer, it is enough to consider the case where these two values are the left and right endpoints. So, during the merge sort, we can update the answer with all the contributions whose differences are as small as possible, and update the original positions.

```cpp
// random.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e6 + 200;

int seq[MAX_N], n, tmp[MAX_N], tmp_pos[MAX_N], pos[MAX_N], ans = 0x3f3f3f3f;

void mergeSort(int l, int r)
{
    if (l == r)
        return;
    int mid = (l + r) >> 1;
    mergeSort(l, mid), mergeSort(mid + 1, r);
    int ptr1 = l, ptr2 = mid + 1, ptr = l;
    while (ptr1 <= mid && ptr2 <= r)
        if (seq[ptr1] < seq[ptr2])
        {
            tmp[ptr] = seq[ptr1], tmp_pos[ptr++] = pos[ptr1], ans = min(ans, max(abs(seq[ptr2] - seq[ptr1]), abs(pos[ptr1] - pos[ptr2]) + 1)), ptr1++;
            continue;
        }
        else
        {
            tmp[ptr] = seq[ptr2], tmp_pos[ptr++] = pos[ptr2], ans = min(ans, max(abs(seq[ptr2] - seq[ptr1]), abs(pos[ptr1] - pos[ptr2]) + 1)), ptr2++;
            continue;
        }
    while (ptr1 <= mid)
        tmp[ptr] = seq[ptr1], tmp_pos[ptr++] = pos[ptr1++];
    while (ptr2 <= r)
        tmp[ptr] = seq[ptr2], tmp_pos[ptr++] = pos[ptr2++];
    for (int i = l; i <= r; i++)
    {
        seq[i] = tmp[i], pos[i] = tmp_pos[i];
        if (i > l)
            ans = min(ans, max(abs(pos[i] - pos[i - 1]) + 1, abs(seq[i] - seq[i - 1])));
    }
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &seq[i]), pos[i] = i;
    mergeSort(1, n), printf("%d", ans);
    return 0;
}
```

## Tree

Every orientation has two directions to choose from. When handling a query, we split apart the two chains from the two points to the $LCA$ and choose opposite directions for them, which a disjoint-set union can take care of. The total number of merges will not exceed $n - 1$, so the complexity is not high. The final answer is $2^{\text{number of connected components}}$.

```cpp
// usmjeri.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 300100, mod = 1e9 + 7;

int head[MAX_N], current, dep[MAX_N], fa[20][MAX_N], n, m, val[MAX_N], mem[MAX_N << 1];
int queries[MAX_N][3];
bool side[MAX_N];

struct edge
{
    int to, nxt;
} edges[MAX_N << 1];

int find(int x)
{
    if (x == mem[x])
        return x;
    int pre = mem[x];
    mem[x] = find(mem[x]);
    side[x] ^= side[pre];
    return mem[x];
}

void unite(int x, int y)
{
    x = find(x);
    while (dep[x] - 2 >= dep[y])
    {
        int tmp = fa[0][x];
        tmp = find(tmp);
        mem[x] = tmp;
        x = find(x);
    }
}

void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}

void dfs(int u, int fat)
{
    fa[0][u] = fat, dep[u] = dep[fat] + 1;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fat)
            dfs(edges[i].to, u);
}

int getLCA(int x, int y)
{
    if (dep[x] < dep[y])
        swap(x, y);
    for (int i = 19; i >= 0; i--)
        if (dep[fa[i][x]] >= dep[y])
            x = fa[i][x];
    if (x == y)
        return x;
    for (int i = 19; i >= 0; i--)
        if (fa[i][x] != fa[i][y])
            x = fa[i][x], y = fa[i][y];
    return fa[0][x];
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= 2 * n; i++)
        mem[i] = i;
    for (int i = 1, u, v; i <= n - 1; i++)
        scanf("%d%d", &u, &v), addpath(u, v), addpath(v, u);
    dfs(1, 0);
    for (int i = 1; i < 20; i++)
        for (int j = 1; j <= n; j++)
            fa[i][j] = fa[i - 1][fa[i - 1][j]];
    for (int id = 1; id <= m; id++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        int lca = getLCA(x, y);
        queries[id][0] = x, queries[id][1] = y, queries[id][2] = lca;
        unite(x, lca), unite(y, lca);
    }
    for (int i = 1; i <= m; i++)
    {
        int x = queries[i][0], y = queries[i][1], lca = queries[i][2];
        if (x == lca || y == lca)
            continue;
        int fx = find(x), fy = find(y);
        if (fx == fy)
        {
            if ((side[x] ^ side[y]) != 1)
                puts("0"), exit(0);
            continue;
        }
        mem[fx] = fy;
        side[fx] = 1 ^ side[x] ^ side[y];
    }
    int ans = 1;
    for (int i = 2; i <= n; i++)
        if (find(i) == i)
            ans = 1LL * ans * 2 % mod;
    printf("%d", ans);
    return 0;
}
```

## Inequality Sequence

Computing it directly is very hard, so we can consider another approach: insert the numbers into the sequence, and then when computing the contributions, the number will adaptively satisfy the inequality conditions. Let the state $dp[i][j]$ be: after inserting $i$ numbers, there are $k$ less-than signs. After inserting, just compute the contributions of the less-than and greater-than cases.

```cpp
// B.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1010, mod = 2012;

int dp[MAX_N][MAX_N], n, k;

int main()
{
    scanf("%d%d", &n, &k);
    dp[1][0] = 1;
    for (int i = 2; i <= n; i++)
        for (int j = 0; j <= min(n - 1, k); j++)
            dp[i][j] = (1LL * dp[i - 1][j - 1] * (i - j) % mod + 1LL * dp[i - 1][j] * (j + 1) % mod) % mod;
    printf("%d", dp[n][k]);
    return 0;
}
```

## Management and Development

This problem really is a <span class="slang" data-zh="神题" data-gloss="shéntí, “god problem”. A brilliantly designed problem, usually a hard one.">godlike problem</span>.

We can derive it backwards: if we repair, multiply the previous answer by a coefficient; developing works the same way.

```cpp
// C.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 100010;

int n, w, ai[MAX_N], bi[MAX_N];
double k, c, ans;

int main()
{
    scanf("%d%lf%lf%d", &n, &k, &c, &w);
    k = 1 - 0.01 * k, c = 1 + 0.01 * c;
    for (int i = 1; i <= n; i++)
        scanf("%d%d", &ai[i], &bi[i]);
    for (int i = n; i >= 1; i--)
        if (ai[i] == 1)
            ans = max(ans, ans * k + bi[i]);
        else
            ans = max(ans, ans * c - bi[i]);
    printf("%.2lf", ans * w);
    return 0;
}
```

## CF292D Connected Components

A prefix disjoint-set union and a suffix disjoint-set union; when answering a query, just merge them by brute force.

```cpp
// CF292D.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 10010;

struct ufs
{
    int fa[550], antiComponentCount;
    int find(int x) { return fa[x] ? fa[x] = find(fa[x]) : x; }
    void unite(int x, int y)
    {
        if (find(x) != find(y))
            antiComponentCount++, fa[find(x)] = find(y);
    }
} lft[MAX_N], rig[MAX_N], ans;

int n, m, xi[MAX_N], yi[MAX_N], q;

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++)
        scanf("%d%d", &xi[i], &yi[i]), lft[i] = lft[i - 1], lft[i].unite(xi[i], yi[i]);
    for (int i = m; i >= 1; i--)
        rig[i] = rig[i + 1], rig[i].unite(xi[i], yi[i]);
    scanf("%d", &q);
    while (q--)
    {
        int l, r;
        scanf("%d%d", &l, &r);
        ans = lft[l - 1];
        for (int i = 1; i <= n; i++)
            if (rig[r + 1].fa[i])
                ans.unite(rig[r + 1].fa[i], i);
        printf("%d\n", n - ans.antiComponentCount);
    }
    return 0;
}
```

## IOI 2008 Island

Maintain the diameter of each pseudotree and add them up.

The trouble is this: maintaining the diameter of a pseudotree means considering two cases, one is the cycle plus two chains, and the other is a single chain. The hard part of the chains on the cycle is that you need a monotonic queue to optimize it; anyway, it is a really <span class="slang" data-zh="毒瘤" data-gloss="dúliú, “tumor”. A problem (or problem setter) that is painfully hard, tedious, or full of traps.">nasty</span> problem.

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

const int MAX_N = 3e6 + 200;

int head[MAX_N], n, deg[MAX_N], current, org[MAX_N], ccnt;
ll chain_dist[MAX_N], dist[MAX_N], dp[MAX_N], ans, q[MAX_N], chain[MAX_N];
bool vis[MAX_N];

struct edge
{
    int to, nxt;
    ll weight;
} edges[MAX_N << 1];

void addpath(int src, int dst, ll weight)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    edges[current].weight = weight, head[src] = current++;
}

void toposort()
{
    queue<int> q;
    for (int i = 1; i <= n; i++)
        if (deg[i] == 1)
            q.push(i);
    while (!q.empty())
    {
        int u = q.front();
        q.pop(), deg[u]--;
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            if (deg[edges[i].to] > 1)
            {
                deg[edges[i].to]--;
                dp[org[u]] = max(dp[org[u]], dist[u] + dist[edges[i].to] + edges[i].weight);
                dist[edges[i].to] = max(dist[edges[i].to], dist[u] + edges[i].weight);
                if (deg[edges[i].to] == 1)
                    q.push(edges[i].to);
            }
    }
}

void dfs(int u, int fat, int og)
{
    org[u] = og;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (!org[edges[i].to])
            dfs(edges[i].to, u, og);
}

void solve(int id, int blk)
{
    int m = 0;
    ll pt = id;
    bool flag = false;
    do
    {
        flag = false, chain[++m] = dist[pt];
        deg[pt] = 1;
        for (int i = head[pt]; i != -1; i = edges[i].nxt)
            if (deg[edges[i].to] > 1)
            {
                flag = true, pt = edges[i].to;
                chain_dist[m + 1] = chain_dist[m] + edges[i].weight;
            }
    } while (flag);
    if (m == 2)
    {
        // 2-node-loop;
        ll mx_len = 0;
        for (int i = head[pt]; i != -1; i = edges[i].nxt)
            if (edges[i].to == id)
                mx_len = max(mx_len, edges[i].weight);
        dp[blk] = max(dp[blk], dist[id] + dist[pt] + mx_len);
        return;
    }
    for (int i = head[pt]; i != -1; i = edges[i].nxt)
        if (edges[i].to == id)
        {
            chain_dist[m + 1] = chain_dist[m] + edges[i].weight;
            break;
        }
    for (int i = 1; i <= m; i++)
        chain[i + m] = chain[i], chain_dist[i + m] = chain_dist[m + 1] + chain_dist[i];
    int head = 1, tail = 1;
    q[1] = 1;
    for (int i = 2; i <= 2 * m; i++)
    {
        while (head <= tail && i - q[head] >= m)
            head++;
        dp[blk] = max(dp[blk], chain[q[head]] + chain[i] + max(chain_dist[i] - chain_dist[q[head]], chain_dist[m + 1] - (chain_dist[i] - chain_dist[q[head]])));
        while (head <= tail && chain[i] - chain_dist[i] >= chain[q[tail]] - chain_dist[q[tail]])
            tail--;
        q[++tail] = i;
    }
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for (int u = 1, v, w; u <= n; u++)
        scanf("%d%d", &v, &w), addpath(u, v, w), addpath(v, u, w), deg[u]++, deg[v]++;
    // done the preprocess;
    for (int i = 1; i <= n; i++)
        if (!org[i])
            dfs(i, 0, ++ccnt);
    toposort();
    // get the loop done;
    for (int i = 1; i <= n; i++)
        if (!vis[org[i]] && deg[i] > 1)
        {
            solve(i, org[i]);
            vis[org[i]] = true, ans += dp[org[i]];
        }
    printf("%lld", ans);
    return 0;
}
```
