---
id: 1714
lang: en
translation_of: index.md
source_sha256: 165039b9fbcc7d9b829e0168cf2af812da7b5844ace627da5ff6cc232da69616
title: "[Miscellaneous Problems] - September 25, 2019"
description: "Short notes on seven problems: articulation points in BLO, Codeforces Round #588 D to F, a linear-time binary tree, a greedy, and 2D partial order."
tags: ["OI","Greedy","Brute Force","Tarjan","Divide and Conquer","Ad Hoc","Counting","Articulation Points","2D Partial Order"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "二位偏序 in the 收作业 section (and in the tags) is a typo for 二维偏序 and is translated as “2D partial order”."
  - "整颗搜索树 is read as 整棵搜索树, “the whole search tree”."
  - "Problem names without an official English title were translated literally: 出行预算 as Travel Budget, 收作业 as Collecting Homework, 树的序 (P1377) as Tree Order."
---

## [POI2008]BLO

At a glance you can tell it is an articulation point problem. For a vertex that is not an articulation point, every pair counted must include this vertex itself, and since the pairs are ordered, the contribution is $2(n - 1)$. If it is an articulation point, things are more troublesome; count it in the following parts:

- Pairs extending out from this vertex.
- Pairs between connected components.
- Pairs that could not reach each other in the first place.

The first one is easy to count: it is $2(n - 1)$. For the second, while Tarjan enumerates the search subtrees, compute the product of the subtree size and the size of its complement in the whole graph (note that this counts the pairs with vertex $u$ one extra time, so we change the first one to count $n - 1$); for the third, compute the product of “the size of the complement of the current whole search tree in the graph” and “the size of the search tree”.

Putting it all together, for vertex $u$:

$$
ans_u = \sum_{k \in son(u)} (n - size(k)) \times size(k) + (n - 1) + (n - 1 - \sum_{k \in son(u)} size(k)) \times (1 + \sum_{k \in son(u)} size(k))
$$

<!--more-->

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

const int MAX_N = 100010, MAX_M = 500010;

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

int head[MAX_N], current, n, m, dfn[MAX_N], low[MAX_N], ptot, siz[MAX_N], root;
ll ans[MAX_N];
bool cut[MAX_N];

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

void tarjan(int u)
{
    ll flag = 0, sum = 0;
    dfn[u] = low[u] = ++ptot, siz[u] = 1;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (dfn[edges[i].to] == 0)
        {
            tarjan(edges[i].to), low[u] = min(low[edges[i].to], low[u]);
            siz[u] += siz[edges[i].to];
            if (low[edges[i].to] >= dfn[u])
            {
                flag++;
                ans[u] += 1LL * (n - siz[edges[i].to]) * siz[edges[i].to];
                // sum accumulated from cut;
                sum += siz[edges[i].to];
                if (u != 1 || flag > 1)
                    cut[u] = true;
            }
        }
        else
            low[u] = min(dfn[edges[i].to], low[u]);
    if (!cut[u])
        ans[u] = 2LL * (n - 1);
    else
        ans[u] += 1LL * (n - sum - 1) * (sum + 1) + (n - 1);
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1, u, v; i <= m; i++)
        scanf("%d%d", &u, &v), addpath(u, v), addpath(v, u);
    tarjan(1);
    for (int i = 1; i <= n; i++)
        printf("%lld\n", ans[i]);
    return 0;
}
```

## Codeforces Round #588 (Div. 2)

### D - Marcin and Training Camp

Consider two cases:

- If the skill Codes are the same, then the two can be considered merged. Just maintain this with a map.
- If the skill Codes are different, then while enumerating in $O(n^2)$, find an $S_i \subseteq S_j$ and mark it, and that is it.

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

using namespace std;

const int MAX_N = 7070;

ll skills[MAX_N], val[MAX_N], n;
bool tag[MAX_N];
map<ll, int> cnt;

int main()
{
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &skills[i]), cnt[skills[i]]++;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &val[i]);
    ll ans = 0;
    for (int i = 1; i <= n; i++)
        // set it as origin;
        if (cnt[skills[i]] > 1)
            for (int j = 1; j <= n; j++)
                if ((skills[i] & skills[j]) == skills[j])
                    tag[j] = true;
    for (int i = 1; i <= n; i++)
        if (tag[i])
            ans += val[i];
    printf("%lld", ans);
    return 0;
}
```

### E - Kamil and Making a Stream

This problem is so clever!

Consider the ordinary brute-force case: $O(n^2)$ chains, just count them directly and you are done. But notice: the $gcd$ going down a chain is always a divisor of the root, and from the argument about the complexity of $\gcd$, we know there can be at most $\log$-many distinct $\gcd$ values. Once we know this property, during the DFS we can take the $gcd$ values of the parent's chains and merge them, multiplying by the occurrence counts, and that is it. This approach is really way too <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">godlike</span>.

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

using namespace std;

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

int head[MAX_N], current;
ll val[MAX_N], ans, n;
map<ll, ll> mps[MAX_N];

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++;
}

ll gcd(ll a, ll b)
{
    if (a == 0 && b == 0)
        return 0;
    if (a == 0)
        return b;
    return b == 0 ? a : gcd(b, a % b);
}

void dfs(int u, int fa)
{
    for (map<ll, ll>::iterator it = mps[fa].begin(); it != mps[fa].end(); it++)
        mps[u][gcd(val[u], it->first)] += it->second;
    mps[u][val[u]]++;
    for (map<ll, ll>::iterator it = mps[u].begin(); it != mps[u].end(); it++)
        ans = (1LL * ans + 1LL * it->second * it->first % mod) % mod;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
            dfs(edges[i].to, u);
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &val[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", ans);
    return 0;
}
```

### F - Konrad and Company Evaluation

Translated, the problem is to dynamically maintain the number of chains of length three. Of course, the queries you are given are bound to be simplified a bit: the direction of every edge depends on how the dynamic weights of its two endpoints compare. The official solution proved, in an extremely <span class="slang" data-zh="日狗" data-gloss="rì gǒu, short for 日了狗 (rì le gǒu), “screwed a dog”. A vulgar exclamation of exasperation or disbelief, like “WTF”.">WTF</span> way, that there are relatively few such edges, so you can just brute-force it. Seriously, <span class="slang" data-zh="日狗" data-gloss="rì gǒu, short for 日了狗 (rì le gǒu), “screwed a dog”. A vulgar exclamation of exasperation or disbelief, like “WTF”.">WTF</span>.

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

using namespace std;

const int MAX_N = 1e5 + 200;

list<int> l2r[MAX_N];
list<int> r2l[MAX_N];

int n, indeg[MAX_N], outdeg[MAX_N], salaries[MAX_N], m, q;

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1, u, v; i <= m; i++)
    {
        scanf("%d%d", &u, &v);
        if (u < v)
            swap(u, v);
        r2l[u].push_back(v), l2r[v].push_back(u);
        outdeg[v]++, indeg[u]++;
    }
    for (int i = 1; i <= n; i++)
        salaries[i] = i;
    ll ans = 0;
    for (int i = 1; i <= n; i++)
        for (list<int>::iterator it = r2l[i].begin(); it != r2l[i].end(); it++)
            ans += indeg[*it];
    printf("%lld\n", ans);
    scanf("%d", &q);
    int days = 0;
    while (q--)
    {
        int u;
        days++, scanf("%d", &u), salaries[u] = n + days;
        ll flip_num = 0;
        for (list<int>::iterator it = l2r[u].begin(); it != l2r[u].end();)
            // if there is a edge needs flipping;
            if (salaries[u] > salaries[*it])
            {
                int id = *it;
                flip_num++;
                indeg[id]--;
                ans -= outdeg[id] - indeg[id];
                outdeg[id]++;
                list<int>::iterator backup = it;
                backup++, l2r[u].erase(it), it = backup;
                l2r[id].push_back(u);
            }
            else
                it++;
        ans += 1LL * (outdeg[u] - flip_num) * (indeg[u] + flip_num) - (1LL * indeg[u] * outdeg[u]);
        indeg[u] += flip_num, outdeg[u] -= flip_num;
        printf("%lld\n", ans);
    }
    return 0;
}
```

## Building a Binary Tree in Linear Time

One way is to build a Cartesian tree, but I do not know how. The other way is the “deque”: add edges from back to front, and since the in-order traversal of this binary tree is fixed, the indices also have to be merged when merging. See this problem: P1377 [TJOI2011] Tree Order.

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

using namespace std;

const int MAX_N = 1e5 + 200;

int seq[MAX_N], pos[MAX_N], lft[MAX_N], rig[MAX_N], n, lson[MAX_N], rson[MAX_N];

void dfs(int u)
{
    if (u == 0)
        return;
    printf("%d ", u);
    dfs(lson[u]), dfs(rson[u]);
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &seq[i]), pos[seq[i]] = i;
        lft[i] = i - 1, rig[i] = i + 1;
    }
    for (int i = n; i >= 2; i--)
    {
        //  connect to the prev or back one;
        int l = lft[seq[i]], r = rig[seq[i]];
        if (pos[l] > pos[r])
            rson[l] = seq[i];
        else
            lson[r] = seq[i];
        lft[r] = l, rig[l] = r;
    }
    dfs(seq[1]);
    return 0;
}
```

## Travel Budget

This one also counts as a good greedy problem. First do the preprocessing, working out things like the distances of the $n$ segments. After that, we go one segment at a time: first, we maintain a node that can always supply cheap fuel, and we also need to know how much of the fuel put in the tank earlier is available for use now; once we know these, we can take greedily, and then just maintain the tank with a segment tree.

```cpp
// B.cpp
#include <bits/stdc++.h>
#define pr pair<double, int>
using namespace std;

const int MAX_N = 500100;

int n;
double D, C, d0, nodes[MAX_N << 2], tag[MAX_N << 2], di[MAX_N], pi[MAX_N], segs[MAX_N];

#define lson (p << 1)
#define rson ((p << 1) | 1)
#define mid ((l + r) >> 1)

void pushdown(int p)
{
    if (tag[p] != 0)
    {
        nodes[lson] += tag[p], nodes[rson] += tag[p];
        tag[lson] += tag[p], tag[rson] += tag[p];
        tag[p] = 0;
    }
}

void pushup(int p)
{
    nodes[p] = nodes[lson] + nodes[rson];
}

void update(int ql, int qr, int l, int r, int p, double val)
{
    if (ql <= l && r <= qr)
        return (void)(nodes[p] += val, tag[p] += val);
    pushdown(p);
    if (ql <= mid)
        update(ql, qr, l, mid, lson, val);
    if (mid < qr)
        update(ql, qr, mid + 1, r, rson, val);
    pushup(p);
}

double query(int ql, int qr, int l, int r, int p)
{
    if (ql <= l && r <= qr)
        return nodes[p];
    double ret = 0;
    if (ql <= mid)
        ret = max(ret, query(ql, qr, l, mid, lson));
    if (mid < qr)
        ret = max(ret, query(ql, qr, mid + 1, r, rson));
    return ret;
}

#undef lson
#undef rson
#undef mid

int main()
{
    scanf("%d%lf%lf%lf", &n, &D, &C, &d0);
    for (int i = 1; i <= n; i++)
        scanf("%lf%lf", &di[i], &pi[i]);
    for (int i = 1; i <= n - 1; i++)
        segs[i] = di[i + 1] - di[i];
    segs[n] = D - di[n];
    priority_queue<pr> pq;
    int lastpos = 0;
    double ans = 0;
    for (int i = 1; i <= n; i++)
    {
        pq.push(make_pair(-pi[i], i));
        double need = segs[i] / d0;
        while (need > 0)
        {
            if (pq.empty())
                puts("Poor Congcong"), exit(0);
            int pos = pq.top().second;
            if (pos <= lastpos)
            {
                pq.pop();
                continue;
            }
            double lft = C - query(pos, i, 1, n, 1);
            if (lft <= 0)
            {
                pq.pop();
                break;
            }
            if (need - lft <= 0)
            {
                ans += need * pi[pos];
                update(pos, i, 1, n, 1, need);
                need = 0;
            }
            else
            {
                ans += lft * pi[pos];
                need -= lft, update(pos, i, 1, n, 1, lft);
                lastpos = max(lastpos, pos);
                pq.pop();
            }
        }
    }
    printf("%.2lf", ans);
    return 0;
}
```

## Collecting Homework

<span class="slang" data-zh="切掉" data-gloss="qiēdiào, “to cut off”. OI slang for solving a problem, getting it accepted.">Knocked it out</span> in the exam. First, the shortest path must be a non-decreasing path; second, there is no need to think about the specific way of transitioning, so we can directly find the points within the range and transition from them. Finished it off with 2D partial order (the first time I wrote this kind of thing in an exam).

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

using namespace std;

inline int read()
{
    int X = 0, w = 0;
    char ch = 0;
    while (!isdigit(ch))
    {
        w |= ch == '-';
        ch = getchar();
    }
    while (isdigit(ch))
        X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}

const int MAX_N = 2e5 + 200;

struct point
{
    int x, y, val, id;
    bool operator<(const point &pt) const { return x < pt.x || (x == pt.x && y < pt.y); }
} pts[MAX_N];

int n, m, k, dp[MAX_N], tree[MAX_N << 1], upper;
vector<int> mpx, mpy;

inline int lowbit(int x) { return x & -x; }

void update(int x, int d)
{
    if (x == 0)
        return;
    for (; x <= upper; x += lowbit(x))
        tree[x] = max(tree[x], d);
}

int query(int x)
{
    int ans = 0;
    for (; x > 0; x -= lowbit(x))
        ans = max(tree[x], ans);
    return ans;
}

int main()
{
    freopen("homework.in", "r", stdin);
    freopen("homework.out", "w", stdout);
    n = read(), m = read(), k = read();
    for (int i = 1; i <= k; i++)
    {
        pts[i].x = read(), pts[i].y = read(), pts[i].val = read(), pts[i].id = i;
        mpx.push_back(pts[i].x), mpy.push_back(pts[i].y);
    }
    pts[k + 1] = point{n - 1, m - 1, 0, k + 1}, k++;
    mpx.push_back(n - 1), mpy.push_back(m - 1);
    sort(mpx.begin(), mpx.end()), sort(mpy.begin(), mpy.end());
    mpx.erase(unique(mpx.begin(), mpx.end()), mpx.end());
    mpy.erase(unique(mpy.begin(), mpy.end()), mpy.end());
    upper = mpy.size();
    for (int i = 1; i <= k; i++)
    {
        pts[i].x = lower_bound(mpx.begin(), mpx.end(), pts[i].x) - mpx.begin() + 1;
        pts[i].y = lower_bound(mpy.begin(), mpy.end(), pts[i].y) - mpy.begin() + 1;
    }
    sort(pts + 1, pts + 1 + k);
    for (int i = 1; i <= k; i++)
    {
        int ans = query(pts[i].y);
        dp[pts[i].id] = ans + pts[i].val;
        update(pts[i].y, dp[pts[i].id]);
    }
    printf("%d", dp[k]);
    return 0;
}
```
