---
id: 2279
lang: en
translation_of: index.md
source_sha256: dedfe5f46890039bb213ba6aaa93b59cd961b0dc7c65ccefdef3ab046aca0cbc
title: "P3589: [POI2015] KUR — Solution"
description: "Each character of the length-m string gives an inequality on the start position; intersect the intervals, then use gcd(a, n) = 1 to count."
tags: ["OI","Math","Number Theory"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The problem name KUR is kept as written (it is the POI problem code)."
---

## Main Idea

At first glance this is hard to do directly. Let's start working from that string of length $m$, and we find that each $01$ corresponds to an inequality condition:

$$
a(s + i) + b < p
$$

where the position in the $m$ string is $i$, and the position in $S$ is $s + i$. After listing all of these, we intersect the intervals, and then notice the property $\gcd(a, n) = 1$, which means $ai \bmod n$ is a one-to-one correspondence, so to count the final values we only need to subtract the qualifying numbers in $[n - m + 1, n - 1]$.

## Code

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

using namespace std;

const int MAX_N = 1e6 + 200;

int n, a, b, p, m, ltot;
char str[MAX_N];
pair<int, int> limits[MAX_N << 2];

void create(int l, int r)
{
    if (l <= r)
        limits[++ltot] = make_pair(l, r);
    else
        limits[++ltot] = make_pair(l, n - 1), limits[++ltot] = make_pair(0, r);
}

int main()
{
    scanf("%d%d%d%d%d%s", &n, &a, &b, &p, &m, str);
    int ans = 0;
    for (int i = 0; i < m; i++)
        if (str[i] == '0')
            create((p + n - 1LL * i * a % n) % n, (0LL + n - 1 - 1LL * i * a % n) % n);
        else
            create((n - 1LL * i * a % n) % n, (p + n - 1LL * i * a % n - 1) % n);
    for (int i = 1; i < m; i++)
        create((0LL + b + n - 1LL * a * i % n) % n, (0LL + b + n - 1LL * a * i % n) % n);
    sort(limits + 1, limits + 1 + ltot);
    int tmp = -1;
    for (int i = 1; i <= ltot; i++)
    {
        if (limits[i].first > tmp)
            ans += limits[i].first - tmp - 1, tmp = limits[i].second;
        else
            tmp = max(tmp, limits[i].second);
    }
    printf("%d\n", ans + n - 1 - tmp);
    return 0;
}
```
