Espiral de Fibonacci rectangular#12370

Espiral de Fibonacci rectangular (Editorial)

Problem Author:

Andriy Kholod (Connect)

Prepared by:

Andriy Kholod (Connect)

Analysis:

Andriy Kholod (Connect)

Idea

Each spiral is defined only by its starting point (x_i,y_i). Everything else about it is the same: the same directions, the same segment lengths, the same angles.

That is, any spiral is simply the same canonical spiral shifted by the vector (x_i,y_i).

Therefore, instead of working with different spirals separately, it is sufficient to:

  • construct one canonical spiral starting at ;

  • for each of its segments, count how many starting points translate this segment to the query point.

1) Canonical Spiral

We will construct a spiral that starts at .

Let its -th segment have one of four directions: [ (1,0),\ (0,1),\ (-1,0),\ (0,-1) ] and the length is f_i.

The code simply simulates the first segments of this polyline and stores:

  • all horizontal and vertical segments;

  • all corner points.

For each segment, the following is stored:

  • its type: horizontal or vertical;

  • the fixed coordinate;

  • the bounds for the second coordinate.

2) Why only the first 55 segments are sufficient

This is a key point.

The starting points of the spirals satisfy: |x_i|, |y_i| \le 10^9 and the query points: |x|, |y| \le 10^7

Thus, if the point lies on a spiral starting at (x_i,y_i), the corresponding point on the canonical spiral has coordinates (x - x_i,\ y - y_i) that is, |x - x_i| \le 1.01 \cdot 10^9, |y - y_i| \le 1.01 \cdot 10^9.

The coordinates of the canonical spiral grow approximately like Fibonacci numbers. After just a few dozen steps, they become significantly larger than 10^9 in absolute value. Therefore, no later segment can yield a point that, after shifting, will fall into any query.

The code takes a reserve of 55 segments, which is more than enough.

3) How to count the contribution of one horizontal segment

Let there be a horizontal segment in the canonical spiral: y = c, x \in [L,R].

After shifting to the starting point (s_x,s_y), it will become: y = s_y + c, x \in [s_x + L,\ s_x + R].

The query point (q_x,q_y) lies on this shifted segment if and only if:

q_y = s_y + c and q_x \in [s_x + L,\ s_x + R].

We can rewrite this as conditions on the starting point:

s_y = q_y - c and s_x \in [q_x - R,\ q_x - L].

That is, for each horizontal segment, the problem reduces to this query:

Count how many starting points have y = q_y - c and x \in [q_x - R,\ q_x - L].

4) How to count the contribution of a vertical segment

Similarly, if the canonical segment is vertical: x = c, y \in [L,R], then after shifting to (s_x,s_y), it will become: x = s_x + c, y \in [s_y + L,\ s_y + R].

The point (q_x,q_y) lies on it if and only if: s_x = q_x - c and s_y \in [q_y - R,\ q_y - L].

That is, we need to count the number of starting points with x = q_x - c and y \in [q_y - R,\ q_y - L].

5) How to quickly count such points

We have the starting points of the spirals: (x_i,y_i).

We can build two arrays:

  • by_X: pairs (x_i,y_i) sorted lexicographically;

  • by_Y: pairs (y_i,x_i) also sorted.

Then:

  • for a vertical segment, we fix and search for all in the range;

  • for a horizontal segment, we fix and search for all in the range.

This is done with two binary searches:

  • lower_bound — the start of the suitable range;

  • upper_bound — the end.

The number of points in this range is added to the answer.

6) Why corners need to be subtracted

If the query point lands exactly on a corner of the spiral, it belongs to two adjacent segments simultaneously. Then we will count the same spiral twice:

  • once through the previous segment;

  • once more through the next one.

Therefore, after counting all segments, we need to subtract the number of spirals for which the query landed on the vertex of the canonical spiral.

This can be maintained with a separate array.

If the vertex of the canonical spiral has coordinates (c_x,c_y), then for the query (q_x,q_y) we search for starting points: (s_x,s_y) = (q_x - c_x,\ q_y - c_y).

The number of such starts has already been counted twice, so it needs to be subtracted once.

9) Asymptotics

Let K=55 — the number of generated segments.

Preprocessing:

  • sorting the starting points — O(n \log n);

  • constructing the canonical spiral — .

One query:

  • we go through all segments;

  • for each, we do O(\log n) through binary searches;

  • separately, we go through all K-1 corners.

Thus, one query works in: O(K \log n), and since is a constant, it is simply O(\log n).

In total: O(n \log n + q \log n).

Solution Code

#include <bits/stdc++.h>
#include <random>
// fast_pragmas

//#pragma GCC optimize("O3")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,tune=native")

// fast_pragmas ended

//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4")
//#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")

using namespace std;

#define ull unsigned long long
#define ll long long
#define ld long double
#define speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define endl '\n'
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define pb push_back
#define ln log
#define lg log10
#define log log2
#define here cout<<"HERE"<<endl

const ll clasik = 5e5 + 7;
const ll mln = 1e6 + 7;
const ll mod = 1e9 + 7;
//const ll mod = 998244353;
const ll block_size = 450;
const ll INF = 1e17;

ll df[clasik];

struct Segment {
    char type;
    ll fixed;
    ll min_val;
    ll max_val;
};

void solve() {
    ll n;
    cin >> n;

    vector<pair<ll, ll>> by_X(n), by_Y(n);

    ll min_x = (ll)2e18, max_x = -(ll)2e18;
    ll min_y = (ll)2e18, max_y = -(ll)2e18;

    for (int i = 0; i < n; i++) {
        ll x, y;
        cin >> x >> y;
        by_X[i] = {x, y};
        by_Y[i] = {y, x};

        min_x = min(min_x, x);
        max_x = max(max_x, x);
        min_y = min(min_y, y);
        max_y = max(max_y, y);
    }

    sort(by_X.begin(), by_X.end());
    sort(by_Y.begin(), by_Y.end());

    vector<ll> f(60);
    f[1] = 1;
    f[2] = 1;
    for (int i = 3; i <= 55; i++) {
        f[i] = f[i - 1] + f[i - 2];
    }

    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};

    vector<Segment> segs;
    vector<pair<ll, ll>> corners;

    ll cx = 0, cy = 0;

    for (int i = 1; i <= 55; i++) {
        ll nx = cx + f[i] * dx[(i - 1) % 4];
        ll ny = cy + f[i] * dy[(i - 1) % 4];

        if ((i - 1) % 2 == 0) {
            segs.pb({'H', cy, min(cx, nx), max(cx, nx)});
        } else {
            segs.pb({'V', cx, min(cy, ny), max(cy, ny)});
        }

        if (i < 55) {
            corners.pb({nx, ny});
        }

        cx = nx;
        cy = ny;
    }

    ll q;
    cin >> q;

    while (q--) {
        ll qx, qy;
        cin >> qx >> qy;
        ll ans = 0;

        for (auto seg : segs) {
            if (seg.type == 'H') {
                ll py = qy - seg.fixed;
                ll px_min = qx - seg.max_val;
                ll px_max = qx - seg.min_val;

                if (py >= min_y && py <= max_y && px_max >= min_x && px_min <= max_x) {
                    auto it_start = lower_bound(by_Y.begin(), by_Y.end(), make_pair(py, px_min));
                    if (it_start != by_Y.end() && it_start->first == py && it_start->second <= px_max) {
                        auto it_end = upper_bound(it_start, by_Y.end(), make_pair(py, px_max));
                        ans += distance(it_start, it_end);
                    }
                }
            } else {
                ll px = qx - seg.fixed;
                ll py_min = qy - seg.max_val;
                ll py_max = qy - seg.min_val;

                if (px >= min_x && px <= max_x && py_max >= min_y && py_min <= max_y) {
                    auto it_start = lower_bound(by_X.begin(), by_X.end(), make_pair(px, py_min));
                    if (it_start != by_X.end() && it_start->first == px && it_start->second <= py_max) {
                        auto it_end = upper_bound(it_start, by_X.end(), make_pair(px, py_max));
                        ans += distance(it_start, it_end);
                    }
                }
            }
        }

        for (auto c : corners) {
            ll px = qx - c.first;
            ll py = qy - c.second;

            if (px >= min_x && px <= max_x && py >= min_y && py <= max_y) {
                auto it_start = lower_bound(by_X.begin(), by_X.end(), make_pair(px, py));
                if (it_start != by_X.end() && it_start->first == px && it_start->second == py) {
                    auto it_end = upper_bound(it_start, by_X.end(), make_pair(px, py));
                    ans -= distance(it_start, it_end);
                }
            }
        }

        cout << ans << endl;
    }
}

signed main() {

    //freopen("deciding_points_input.txt" , "r" , stdin);
    //freopen("outputA.txt" , "w" , stdout);

    speed;
    int test;
    test = 1;
    //precalc();
    //cin >> test;
    for (int tt = 1; tt <= test; tt++) {
        //cout << "Case #" << tt << ": ";
        solve();
    }

    return 0;
}