---
id: 2138
lang: en
translation_of: index.md
source_sha256: 1c111f8bd48f1dd2148fd8e17179cbdde7919fd862ad78ff3242727db8d6d02c
title: "POI Selected Problems"
description: "Short notes and code for a pile of POI problems I liked before CSP but never got around to writing."
tags: ["OI","DP","Greedy","Gaussian Elimination","Segment Tree","Divisor-Block Decomposition","Constructive","POI","Hall's Theorem","DAG DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "坑 in 所以就有了这个坑 is used in its project sense (an unfinished series one has started), not the “screwed me over” sense chipped elsewhere, so the fuller phrase 这个坑 is chipped with its own gloss."
  - "切掉 in the Monotonicity section is literal (cutting the answer in the middle), not the OI slang for solving a problem, so it gets no chip."
  - "权值线段树 rendered as “value-indexed segment tree”."
---

## Overview

I suddenly remembered there was still a whole pile of POI problems I really liked before CSP that I never wrote, hence <span class="slang" data-zh="这个坑" data-gloss="zhège kēng, “this pit”. A 坑 is a project or series one has started and still has to fill in, i.e. finish.">this pit</span>.

<!--more-->

## [POI2015] TRZ

It's quite a pain to write.

Let's first write out the conditions:

$$
\begin{cases} s_r^1 - s_{l - 1}^1 \neq s_r^2 - s_{l - 1}^2 \neq s_r^2 - s_{l - 1}^2 \neq s_r^1 - s_{l - 1}^1 \end{cases}
$$

After moving terms around, we find they can be turned into features of each point itself:

$$
\begin{cases} s_r^1 - s_r^2 \neq s_{l - 1}^1 - s_{l - 1}^2 \\ s_r^1 - s_r^3 \neq s_{l - 1}^1 - s_{l - 1}^3 \\ s_r^2 - s_r^3 \neq s_{l - 1}^2 - s_{l - 1}^3 \end{cases}
$$

We need to find the longest interval for which this condition holds, so really this is a partial order problem. For every 3D point, just turn each dimension directly into its feature. But this partial order needs to know all the information except the point itself, so it can't be handled like a normal partial order. So, let's piece something together. Consider sorting by $x$, then inserting $y$ into a value-indexed segment tree, and finally having each node maintain the extreme positions of two different $z$ values. A bit hard to write.

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

using namespace std;

const int MAX_N = 1e6 + 200, INF = 0x3f3f3f3f;

int n, ans, ptot = 1;
char str[MAX_N];

struct node
{
    int lson, rson, max_val[2] = {-1, -1}, min_val[2] = {INF, INF};
} nodes[MAX_N * 3];

struct package
{
    int id, x, y, z;
    bool operator<(const package &rhs) const { return x < rhs.x; }
} pre[MAX_N], ai[MAX_N], bi[MAX_N];

int update(int qx, int l, int r, int p, package val)
{
    if (p == 0)
        p = ++ptot;
    if (nodes[p].min_val[0] > val.id)
    {
        if (nodes[p].min_val[0] != INF && bi[nodes[p].min_val[0]].id != val.z)
            nodes[p].min_val[1] = nodes[p].min_val[0];
        nodes[p].min_val[0] = val.id;
    }
    else if (nodes[p].min_val[1] > val.id && bi[nodes[p].min_val[0]].z != val.z)
        nodes[p].min_val[1] = val.id;
    if (nodes[p].max_val[0] < val.id)
    {
        if (nodes[p].max_val[0] != -1 && bi[nodes[p].max_val[0]].z != val.z)
            nodes[p].max_val[1] = nodes[p].max_val[0];
        nodes[p].max_val[0] = val.id;
    }
    else if (nodes[p].max_val[1] < val.id && bi[nodes[p].max_val[0]].z != val.z)
        nodes[p].max_val[1] = val.id;
    if (l == r)
        return p;
    int mid = (l + r) >> 1;
    if (qx <= mid)
        nodes[p].lson = update(qx, l, mid, nodes[p].lson, val);
    else
        nodes[p].rson = update(qx, mid + 1, r, nodes[p].rson, val);
    return p;
}

int query(int ql, int qr, int l, int r, int p, package val)
{
    if (p == 0)
        return 0;
    if (ql <= l && r <= qr)
    {
        int min_val, max_val;
        if (nodes[p].min_val[0] == INF)
            return 0;
        min_val = (val.z == bi[nodes[p].min_val[0]].z) ? nodes[p].min_val[1] : nodes[p].min_val[0];
        max_val = (val.z == bi[nodes[p].max_val[0]].z) ? nodes[p].max_val[1] : nodes[p].max_val[0];
        if (min_val == INF || max_val == -1)
            return 0;
        return max(abs(val.id - min_val), abs(val.id - max_val));
    }
    int mid = (l + r) >> 1, ret = 0;
    if (ql <= mid)
        ret = max(ret, query(ql, qr, l, mid, nodes[p].lson, val));
    if (mid < qr)
        ret = max(ret, query(ql, qr, mid + 1, r, nodes[p].rson, val));
    return ret;
}

int main()
{
    scanf("%d%s", &n, str);
    for (int i = 0, ptr = 0; i < n; i++)
    {
        if (str[i] != str[ptr])
            ptr = i;
        ans = max(ans, i - ptr + 1);
    }
    for (int i = 1; i <= n; i++)
    {
        pre[i] = pre[i - 1];
        if (str[i - 1] == 'C')
            pre[i].x++;
        if (str[i - 1] == 'B')
            pre[i].y++;
        if (str[i - 1] == 'S')
            pre[i].z++;
    }
    int lower = 0;
    for (int i = 1; i <= n; i++)
    {
        ai[i].x = pre[i].x - pre[i].y;
        ai[i].y = pre[i].x - pre[i].z;
        ai[i].z = pre[i].y - pre[i].z;
        lower = min(lower, min(ai[i].x, min(ai[i].y, ai[i].z)));
        ai[i].id = i;
    }
    n++;
    for (int i = 1; i <= n; i++)
        ai[i].x -= lower - 1, ai[i].y -= lower - 1, ai[i].z -= lower - 1;
    for (int i = 1; i <= n; i++)
        bi[i] = ai[i];
    bi[0] = bi[n], sort(ai + 1, ai + 1 + n);
    int domain = n - lower + 1;
    for (int i = 1, ptr = 1; i <= n; i++)
    {
        if (ai[i].x != ai[ptr].x)
            ptr = i;
        if (ai[i].x != ai[i + 1].x)
        {
            for (int j = ptr; j <= i; j++)
                ans = max(ans, max(query(1, ai[j].y - 1, 1, domain, 1, ai[j]), query(ai[j].y + 1, domain, 1, domain, 1, ai[j])));
            for (int j = ptr; j <= i; j++)
                update(ai[j].y, 1, domain, 1, ai[j]);
        }
    }
    printf("%d\n", ans);
    return 0;
}
```

## [POI2009] LYZ

I hadn't learned Hall's theorem before, and later found the result is fairly obvious: for any set $U$ of left vertices, the maximal set $S$ of right vertices connected to it must satisfy $|U| \leq |S|$. With small constraints this problem can obviously be done directly with bipartite matching, but the current data doesn't allow that, and it asks us to maintain whether a perfect matching exists. First, we notice that in the worst case there is an interval $[l, r]$ satisfying:

$$
\sum_{i = l}^r X_i > (r - l + 1 + d) k
$$

Moving terms gives:

$$
\sum_{i = l}^r (X_i - k) > d \times k
$$

Just use a segment tree to find such a segment.

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

using namespace std;

const int MAX_N = 5e5 + 200;

typedef long long ll;

int n, m, k, d;

struct node
{
    ll lft, rig, sum, seg;
} nodes[MAX_N << 2];

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

void pushup(int p)
{
    nodes[p].sum = nodes[lson].sum + nodes[rson].sum;
    nodes[p].lft = max(nodes[lson].lft, nodes[lson].sum + nodes[rson].lft);
    nodes[p].rig = max(nodes[rson].rig, nodes[rson].sum + nodes[lson].rig);
    nodes[p].seg = max(nodes[lson].rig + nodes[rson].lft, max(nodes[lson].seg, nodes[rson].seg));
}

void build(int l, int r, int p)
{
    if (l == r)
    {
        nodes[p] = node{0, 0, -k, -k};
        return;
    }
    build(l, mid, lson), build(mid + 1, r, rson);
    pushup(p);
}

void update(int qx, int l, int r, int p, int val)
{
    if (l == r)
    {
        nodes[p].sum += val, nodes[p].seg += val;
        nodes[p].lft = nodes[p].rig = max(0LL, nodes[p].sum);
        return;
    }
    if (qx <= mid)
        update(qx, l, mid, lson, val);
    else
        update(qx, mid + 1, r, rson, val);
    pushup(p);
}

#undef mid
#undef rson
#undef lson

int main()
{
    scanf("%d%d%d%d", &n, &m, &k, &d), build(1, n, 1);
    for (int i = 1; i <= m; i++)
    {
        int xpos, val;
        scanf("%d%d", &xpos, &val), update(xpos, 1, n, 1, val);
        puts(nodes[1].seg <= 1LL * d * k ? "TAK" : "NIE");
    }
    return 0;
}
```

## [POI2014] KAR

It reminds me of a <span class="slang" data-zh="SB" data-gloss="Initials of 傻逼 (shǎbī). A vulgar insult, roughly “idiot” or “stupid”.">stupid</span> Group A problem I did at Jizhong, which is pretty similar to this one. We find that things between intervals can be maintained directly, so just throw a segment tree at it.

```cpp
// P3569.cpp
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 4e5 + 200;

int n, ai[MAX_N][2], q;
bool nodes[MAX_N << 2][2][2];

inline char nc()
{
    static char buf[100000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

int read()
{
    int x = 0, f = 1;
    char ch = nc();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = nc();
    }
    while (isdigit(ch))
        x = (x << 3) + (x << 1) + ch - '0', ch = nc();
    return x * f;
}

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

inline void pushup(int p, int l, int r)
{
    nodes[p][0][0] = nodes[p][1][0] = nodes[p][0][1] = nodes[p][1][1] = false;
    for (register int a = 0; a < 2; a++)
        for (register int b = 0; b < 2; b++)
            for (register int c = 0; c < 2; c++)
                for (register int d = 0; d < 2; d++)
                    nodes[p][a][d] |= nodes[lson][a][c] && nodes[rson][b][d] && ai[mid][c] <= ai[mid + 1][b];
}

inline void update(int qx, int l, int r, int p)
{
    if (l == r)
        return;
    if (qx <= mid)
        update(qx, l, mid, lson);
    else
        update(qx, mid + 1, r, rson);
    pushup(p, l, r);
}

inline void build(int l, int r, int p)
{
    if (l == r)
    {
        nodes[p][0][0] = nodes[p][1][1] = true;
        return;
    }
    build(l, mid, lson), build(mid + 1, r, rson);
    pushup(p, l, r);
}

#undef mid
#undef rson
#undef lson

int main()
{
    n = read();
    for (register int i = 1; i <= n; i++)
        ai[i][0] = read(), ai[i][1] = read();
    q = read(), build(1, n, 1);
    while (q--)
    {
        int x = read(), y = read();
        swap(ai[x][0], ai[y][0]), swap(ai[x][1], ai[y][1]);
        update(x, 1, n, 1), update(y, 1, n, 1);
        puts(nodes[1][0][0] || nodes[1][0][1] || nodes[1][1][0] || nodes[1][1][1] ? "TAK" : "NIE");
    }
    return 0;
}
```

## [POI2014] KLO

We consider placing them alternately, using a heap keyed by size to maintain the available options. Note that we try to put the block with the same color as the end first. Each time, pick the largest block or the second-largest block to place, then check.

```cpp
// P3569.cpp
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 4e5 + 200;

int n, ai[MAX_N][2], q;
bool nodes[MAX_N << 2][2][2];

inline char nc()
{
    static char buf[100000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

int read()
{
    int x = 0, f = 1;
    char ch = nc();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = nc();
    }
    while (isdigit(ch))
        x = (x << 3) + (x << 1) + ch - '0', ch = nc();
    return x * f;
}

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

inline void pushup(int p, int l, int r)
{
    nodes[p][0][0] = nodes[p][1][0] = nodes[p][0][1] = nodes[p][1][1] = false;
    for (register int a = 0; a < 2; a++)
        for (register int b = 0; b < 2; b++)
            for (register int c = 0; c < 2; c++)
                for (register int d = 0; d < 2; d++)
                    nodes[p][a][d] |= nodes[lson][a][c] && nodes[rson][b][d] && ai[mid][c] <= ai[mid + 1][b];
}

inline void update(int qx, int l, int r, int p)
{
    if (l == r)
        return;
    if (qx <= mid)
        update(qx, l, mid, lson);
    else
        update(qx, mid + 1, r, rson);
    pushup(p, l, r);
}

inline void build(int l, int r, int p)
{
    if (l == r)
    {
        nodes[p][0][0] = nodes[p][1][1] = true;
        return;
    }
    build(l, mid, lson), build(mid + 1, r, rson);
    pushup(p, l, r);
}

#undef mid
#undef rson
#undef lson

int main()
{
    n = read();
    for (register int i = 1; i <= n; i++)
        ai[i][0] = read(), ai[i][1] = read();
    q = read(), build(1, n, 1);
    while (q--)
    {
        int x = read(), y = read();
        swap(ai[x][0], ai[y][0]), swap(ai[x][1], ai[y][1]);
        update(x, 1, n, 1), update(y, 1, n, 1);
        puts(nodes[1][0][0] || nodes[1][0][1] || nodes[1][1][0] || nodes[1][1][1] ? "TAK" : "NIE");
    }
    return 0;
}
```

## [POI2010] Monotonicity

First, we can double the sign sequence, and then consider doing DP with the usual subsequence-matching routine. Here we only need a single dimension, that is, we don't record the length of the subsequence, because we can notice that the longest answer, cut off in the middle, still satisfies optimal substructure ([proof](https://blog.csdn.net/kanosword/article/details/52735717)), so there's no need to record it; throw in a Fenwick tree and you're done.

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

using namespace std;

const int MAX_N = 1e6 + 200, MAX_M = 5e6 + 200;

int n, m, ai[MAX_N], nodes[3][MAX_M], dp[MAX_N];
char str[MAX_N];

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

void update(int idx, int x, int d)
{
    for (; x < MAX_M; x += lowbit(x))
        nodes[idx][x] = max(nodes[idx][x], d);
}

int query(int idx, int x, int ret = 0)
{
    for (; x; x -= lowbit(x))
        ret = max(ret, nodes[idx][x]);
    return ret;
}

int main()
{
    char tmp[2];
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &ai[i]);
    for (int i = 1; i <= m; i++)
        scanf("%s", tmp), str[i] = tmp[0];
    for (int i = m + 1; i <= n; i++)
        str[i] = str[(i - 1) % m + 1];
    int ans = 0;
    for (int i = 1; i <= n; i++)
    {
        dp[i] = max(nodes[2][ai[i]], max(query(0, ai[i] - 1), query(1, MAX_M - ai[i]))) + 1;
        ans = max(ans, dp[i]);
        if (str[dp[i]] == '=')
            nodes[2][ai[i]] = max(nodes[2][ai[i]], dp[i]);
        else if (str[dp[i]] == '<')
            update(0, ai[i], dp[i]);
        else
            update(1, MAX_M - ai[i] + 1, dp[i]);
    }
    printf("%d\n", ans);
    return 0;
}
```

## [POI2005] DWA-Two Parties

Now this problem is really <span class="slang" data-zh="骚" data-gloss="sāo, “flirty, showy”. Slang praise for something flashy, clever and unconventional.">slick</span>.

First, there's a known result: you can always find a partition in which every vertex in one of the sets is attached to an even number of edges, and which is an optimal solution. Knowing this, we can try giving each vertex a state $x_i$, representing its set ID (0/1). That way we can turn it into a system of XOR equations, then get a solution with Gaussian elimination.

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

using namespace std;

const int MAX_N = 220;

int n, deg[MAX_N], mat[MAX_N][MAX_N];

int main()
{
    scanf("%d", &n);
    for (int i = 1, tot, v; i <= n; i++)
    {
        scanf("%d", &tot);
        while (tot--)
            scanf("%d", &v), mat[i][v] = 1, deg[i]++;
        if (deg[i] & 1)
            mat[i][i] = mat[i][n + 1] = 1;
    }
    for (int i = 1; i <= n; i++)
    {
        int key = i;
        for (int j = i + 1; j <= n; j++)
            if (mat[j][i] != 0)
            {
                key = j;
                break;
            }
        if (key != i)
            for (int j = i; j <= n + 1; j++)
                swap(mat[i][j], mat[key][j]);
        for (int j = i + 1; j <= n; j++)
            if (mat[j][i] == 1)
                for (int k = i; k <= n + 1; k++)
                    mat[j][k] ^= mat[i][k];
    }
    mat[n][n] = 1;
    // reverse;
    for (int i = n - 1; i >= 1; i--)
    {
        for (int j = i + 1; j <= n; j++)
            if (mat[i][j] != 0)
                for (int k = j; k <= n + 1; k++)
                    mat[i][k] ^= mat[j][k];
        mat[i][i] = 1;
    }
    int tot = 0;
    for (int i = 1; i <= n; i++)
        tot += mat[i][n + 1];
    printf("%d\n", tot);
    for (int i = 1; i <= n; i++)
        if (mat[i][n + 1])
            printf("%d ", i);
    puts("");
    return 0;
}
```

## [POI2012] STU-Well

Rough idea: first binary search on that difference, then compute the cost of zeroing each position, and then find the smallest position.

So how do we quickly compute the cost of zeroing each position? First, we can compute the minimum cost of making the whole array valid, by sweeping once forward and once backward to ensure $|a_i - a_{i + 1}| \leq mid$. When enumerating $k$, we can compute the contribution for the left and right sides separately. Taking the left side as an example, find a position with $a_{L} > (k - L)mid$; then the sum of the part $[L, i - 1]$ minus the sum of the arithmetic sequence is part of the contribution. I thought for a while about why this is correct, and found that if $a_{L} > (k - L)mid$, then even if this interval isn't arithmetic, when we take the interval sum minus the arithmetic sequence sum, the “over-deducted” part gets deducted from $a_L$. The right side works the same way.

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

using namespace std;

typedef long long ll;

const int MAX_N = 1e6 + 200;

int n;
ll m, xi[MAX_N], ai[MAX_N], pre[MAX_N], prefix[MAX_N], suffix[MAX_N];

int check(int mid)
{
    ai[1] = xi[1];
    for (int i = 2; i <= n; i++)
        ai[i] = min(ai[i - 1] + mid, xi[i]);
    for (int i = n - 1; i >= 1; i--)
        ai[i] = min(ai[i + 1] + mid, ai[i]);
    ll acc = 0;
    for (int i = 1; i <= n; i++)
        acc += xi[i] - ai[i], pre[i] = pre[i - 1] + ai[i];
    if (acc > m)
        return 0;
    for (int i = 1, ptr = 1; i <= n; i++)
    {
        while (ptr < i && ai[ptr] <= 1LL * (i - ptr) * mid)
            ptr++;
        prefix[i] = pre[i - 1] - pre[ptr - 1] - 1LL * (i - ptr) * (i - ptr + 1) / 2 * mid;
    }
    for (int i = n, ptr = n; i >= 1; i--)
    {
        while (ptr > i && ai[ptr] <= 1LL * (ptr - i) * mid)
            ptr--;
        suffix[i] = pre[ptr] - pre[i] - 1LL * (ptr - i) * (ptr - i + 1) / 2 * mid;
    }
    for (int i = 1; i <= n; i++)
        if (prefix[i] + suffix[i] + acc + ai[i] <= m)
            return i;
    return 0;
}

int main()
{
    scanf("%d%lld", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &xi[i]);
    int l = 0, r = 1e9, res = 0;
    while (l <= r)
    {
        int mid = (l + r) >> 1;
        if (check(mid))
            r = mid - 1, res = mid;
        else
            l = mid + 1;
    }
    printf("%d %d\n", check(res), res);
    return 0;
}
```

## [POI2014] PAN-Solar Panels

The problem roughly asks you to find, on the 2D plane, the largest $d$ such that $x = kd, y = kd$ happen to have an intersection point inside this rectangle. We find that the condition for an intersection point is:

$$
\begin{gathered} \lfloor \frac{smax}{d} \rfloor - \lfloor \frac{smin - 1}{d} \rfloor > 0 \\ \lfloor \frac{wmax}{d} \rfloor - \lfloor \frac{wmin - 1}{d} \rfloor > 0 \end{gathered}
$$

Then we can just do some divisor-block decomposition, taking the right endpoint as the answer each time.

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

using namespace std;

int T, smin, smax, wmin, wmax;

inline char nc()
{
    static char buf[1000000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin), p1 == p2) ? EOF : *p1++;
}

int read()
{
    int x = 0, f = 1;
    char ch = nc();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = nc();
    }
    while (isdigit(ch))
        x = (x << 3) + (x << 1) + ch - '0', ch = nc();
    return x * f;
}

int main()
{
    scanf("%d", &T);
    while (T--)
    {
        smin = read(), smax = read(), wmin = read(), wmax = read();
        smin--, wmin--;
        int ans = 0;
        for (int d = 1, gx; d <= min(smax, wmax); d = gx + 1)
        {
            gx = min({smax / (smax / d), wmax / (wmax / d)});
            if (int(smin / d) != 0)
                gx = min(gx, smin / (smin / d));
            if (int(wmin / d) != 0)
                gx = min(gx, wmin / (wmin / d));
            if ((smax / d) - (smin / d) > 0 && (wmax / d) - (wmin / d) > 0)
                ans = gx;
        }
        printf("%d\n", ans);
    }
    return 0;
}
```

## [POI2015] PUS

The classic segment-tree-optimized graph construction: brute-force split into $k + 1$ intervals, then run a DAG DP.

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

using namespace std;

const int MAX_N = 6e5 + 200, MAX_E = 8e6 + 200;

int n, s, m, dp[MAX_N], head[MAX_N], current, sidx[MAX_N], ptot, deg[MAX_N], topoidx[MAX_N], topotot;
bool isFixed[MAX_N];

struct edge
{
    int to, nxt, weight;
} edges[MAX_E];

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

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

void build(int l, int r, int p)
{
    ptot = max(ptot, p);
    if (l == r)
        return (void)(sidx[l] = p);
    addpath(p, lson, 0), addpath(p, rson, 0);
    build(l, mid, lson), build(mid + 1, r, rson);
}

void update(int ql, int qr, int l, int r, int p, int src)
{
    if (ql > qr)
        return;
    if (ql <= l && r <= qr)
        return (void)(addpath(src, p, 0));
    if (ql <= mid)
        update(ql, qr, l, mid, lson, src);
    if (mid < qr)
        update(ql, qr, mid + 1, r, rson, src);
}

#undef mid
#undef rson
#undef lson

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d%d", &n, &s, &m), build(1, n, 1);
    for (int i = 1; i <= n; i++)
        dp[sidx[i]] = 1;
    for (int i = 1, p, d; i <= s; i++)
        scanf("%d%d", &p, &d), dp[sidx[p]] = d, isFixed[sidx[p]] = true;
    while (m--)
    {
        int l, r, k, cpt, last = l - 1;
        scanf("%d%d%d", &l, &r, &k), cpt = ++ptot, last = l - 1;
        for (int i = 1, pt; i <= k; i++)
            scanf("%d", &pt), addpath(sidx[pt], cpt, 1), update(last + 1, pt - 1, 1, n, 1, cpt), last = pt;
        update(last + 1, r, 1, n, 1, cpt);
    }
    queue<int> q;
    for (int i = 1; i <= ptot; i++)
        if (deg[i] == 0)
            q.push(i);
    while (!q.empty())
    {
        int u = q.front();
        q.pop(), topoidx[++topotot] = u;
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            if (--deg[edges[i].to] == 0)
                q.push(edges[i].to);
    }
    for (int i = 1; i <= ptot; i++)
        if (deg[i] != 0)
            puts("NIE"), exit(0);
    for (int id = ptot; id >= 1; id--)
    {
        int u = topoidx[id], max_val = 1;
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            max_val = max(max_val, dp[edges[i].to] + edges[i].weight);
        if (isFixed[u] && max_val > dp[u])
            puts("NIE"), exit(0);
        else if (!isFixed[u])
            dp[u] = max_val;
    }
    for (int i = 1; i <= n; i++)
        if (dp[sidx[i]] > 1e9 || dp[sidx[i]] < 1)
            puts("NIE"), exit(0);
    puts("TAK");
    for (int i = 1; i <= n; i++)
        printf("%d%c", dp[sidx[i]], " \n"[i == n]);
    return 0;
}
```
