#if !defined  HAVE_PERM_GENUS0_ARRAY_H__
#define       HAVE_PERM_GENUS0_ARRAY_H__
// This file is part of the FXT library.
// Copyright (C) 2026 Joerg Arndt
// License: GNU General Public License version 3 or later,
// see the file COPYING.txt in the main directory.

#include "comb/comb-print.h"  // print_vec()
#include "perm/printcycles.h"  // print_cycles()
#include "bits/bitlow.h"  // lowest_one_idx()

#include "fxttypes.h"
#include "jjassert.h"

// code and algorithm generated with AI (Claude Opus 5.5)

#define PERM_GENUS0_ARRAY_OPT  // speedup by a factor of about 1.25
// Limit: with PERM_GENUS0_ARRAY_OPT, n <= 63 is required (checked in the
// constructor), as positions 0..n-1 and the value n are bits of a word
// (bit masks Z, GU[], LO[], HI[], all).  Without it, n is not limited.
// The limit is no restriction for generating all objects: there are
// Catalan(n) of them, at about 200 million per second this takes
// 32 seconds for n=20, 6.5 hours for n=25, 7 months for n=30, and
// 400000 years for n=40.  It only matters when generating a part of the
// objects for larger n.

// Force inlining of next() (with PERM_GENUS0_ARRAY_OPT): at -O2 g++ does
// not inline it otherwise (too large for its heuristics), the function
// call then makes generation much slower (141 instead of 208 M/s).
#if defined __GNUC__  // g++ and clang++
#define PERM_GENUS0_ARRAY_INLINE  __attribute__((always_inline))
#else
#define PERM_GENUS0_ARRAY_INLINE
#endif


class perm_genus0_array
// Permutations of genus 0 of n elements, in array form, lexicographic order.
// There are Catalan(n) such permutations: 1, 1, 2, 5, 14, 42, 132, ...
// (OEIS sequence A000108).
//
// A permutation of genus 0 is a noncrossing set partition where each block
// {a1 < a2 < ... < ak} is read as the increasing cycle (a1, a2, ..., ak),
// i.e., P[a1]=a2, P[a2]=a3, ..., P[ak]=a1.
//
// Structure used (reading P from left to right):
// for an element k with P[k] > k we call (k, P[k]) an arc; by noncrossing
// all arcs are nested or disjoint.  Element P[k] is the target of the arc.
// Every element k lies in a "gap" of an enclosing block (or at top level),
// let U[k] be the end of that gap (U[k] = n at top level).
// Then the possible values of P[k] are exactly
//   B[k]  (where B[k] = min of block of k;  B[k]==k: fixed point, else
//          k is the last element of its block and closes the cycle),
//   k+1, k+2, ..., U[k]-1  (forward arc, block of k continues),
// and every such choice can be completed.  The value B[k] (<= k) is the
// smallest, so in lex order the choices for P[k] are
//   B[k], k+1, k+2, ..., U[k]-1.
//
// Lex-minimal completion of a prefix: every element that is the target of
// a pending arc closes its cycle, all others are fixed points.
//
// The data (B[], U[]) of elements that are targets of arcs starting
// before position k remain valid when P[k,...,n-1] changes, this allows
// the update (in next()) without any stack or undo operations.
//
// With PERM_GENUS0_ARRAY_OPT (needs n <= 63, see top of file; for larger
// n compile with -DPERM_GENUS0_ARRAY_NOOPT):
//  - Instead of U[] we keep for each position y the bit mask GU[y] of the
//    chain of gap ends U[y], U[U[y]], ..., n (so U[y] is the lowest bit).
//    The gap ends of the new completion in next() are then simply
//    G = {j} + GU[k], without walking through the chain.
//  - A bit mask Z of the positions k where P[k] can be increased is kept;
//    it is updated in O(1) from G: a position y > k can be increased
//    iff y+1 is not a gap end.  The search for the rightmost such position
//    is a loop over the bits of Z (no memory access); being a loop with
//    branches, the CPU predicts it well (a count-leading-zeros
//    instruction would be fewer instructions, but makes the next call
//    wait for the result of this one: measured slower).
//  - B[] is only kept up to date for targets of arcs (B[k] != k),
//    the fill of new fixed points does not write B[].
//
// Algorithm A (Permutations of genus 0, lexicographic order; this is the
// unoptimized next(), without PERM_GENUS0_ARRAY_OPT).
// Given n >= 1, visit all permutations P[0], ..., P[n-1] of genus 0 in
// lexicographic order of the array form.  Auxiliary arrays: B[k] is the
// minimum of the block (cycle) of k, U[k] is the end of the gap containing
// k (the next element of the enclosing block, or n at top level).
//   A1. [Initialize.]  Set P[k] <- k, B[k] <- k, U[k] <- n for 0 <= k < n.
//   A2. [Visit.]  Visit P[0], ..., P[n-1].
//   A3. [Find k.]  Set k <- n-1.
//   A4. [Can P[k] increase?]  Set j <- max(P[k], k) + 1.  (The value
//       following P[k] in the order B[k], k+1, ..., U[k]-1 of choices.)
//       If j < U[k], go to A5.  Otherwise, if k = 0 terminate, else set
//       k <- k-1 and repeat this step.
//   A5. [Increase P[k].]  Set u <- U[k], b <- B[k], P[k] <- j.
//       (The block of k continues with j; arc (k, j).)
//   A6. [Fill the arc.]  For k < y < j set P[y] <- y, B[y] <- y, U[y] <- j.
//       (Elements inside the new arc become fixed points.)
//   A7. [Close at j.]  Set P[j] <- b, B[j] <- b, U[j] <- u, x <- j.
//       (Element j joins the block of k and closes its cycle.)
//   A8. [Fill the gap.]  Set v <- U[x].  For x < y < v set P[y] <- y,
//       B[y] <- y, U[y] <- v.
//   A9. [Next pending arc.]  If v = n, go to A2.  Otherwise set x <- v,
//       P[x] <- B[x] (target of an arc starting before k: close its cycle,
//       B[x] and U[x] are still valid), and go to A8.
// Steps A6-A9 set P[k+1], ..., P[n-1] to the lex-minimal completion.
// Measured (n=16): per object, 3.67 executions of step A4 on average,
// and about 2.8 entries of P change; the rate of generation does not
// drop with n (constant amortized time, observed, not proved here).
{
private:
    ulong n;   // Number of elements, permutation of {0, 1, ..., n-1}
    ulong *P;  // permutation in array form
    ulong *B;  // B[k] = minimum of the block (cycle) containing k
#if defined PERM_GENUS0_ARRAY_OPT
               //   (only kept up to date for targets of arcs)
    ulong *GU; // GU[k] = bit mask of gap ends U[k], U[U[k]], ..., n
    ulong Z;   // bit k set iff P[k] can be increased
    ulong all; // bit mask with bits 0, 1, ..., n-1 set
    ulong LO[64];  // LO[k] = bit mask of positions 0, 1, ..., k-1
    ulong HI[64];  // HI[k] = bit mask of positions k+1, k+2, ..., n-1
#else
    ulong *U;  // U[k] = end of the gap (of the enclosing block) containing k, or n
#endif

    perm_genus0_array(const perm_genus0_array&) = delete;
    perm_genus0_array & operator = (const perm_genus0_array&) = delete;
public:
    explicit perm_genus0_array(ulong tn)
    {
        n = tn;
        P = new ulong[n+1];  // one extra element (never used) for n==0
        B = new ulong[n+1];
#if defined PERM_GENUS0_ARRAY_OPT
        jjassert( n <= 63 );  // positions and value n must fit into a word
        GU = new ulong[n+1];
        all = (1UL << n) - 1;
        for (ulong k=0; k<64; ++k)
        {
            LO[k] = ( k ? (1UL << k) - 1 : 0 );
            HI[k] = ( k+1 < 64 ? all & ~((2UL << k) - 1) : 0 );
        }
#else
        U = new ulong[n+1];
#endif
        first();
    }

    ~perm_genus0_array()
    {
        delete [] P;
        delete [] B;
#if defined PERM_GENUS0_ARRAY_OPT
        delete [] GU;
#else
        delete [] U;
#endif
    }

    const ulong* data()  const  { return P; }
    ulong size()  const  { return n; }

    void first()
    // Identity permutation: all fixed points, all at top level.
    {
#if defined PERM_GENUS0_ARRAY_OPT
        for (ulong k=0; k<n; ++k)  { P[k] = k;  B[k] = k;  GU[k] = 1UL << n; }
        Z = ( n ? all >> 1 : 0 );  // fixed point k can be increased iff k+1 < n
#else
        for (ulong k=0; k<n; ++k)  { P[k] = k;  B[k] = k;  U[k] = n; }
#endif
    }

#if defined PERM_GENUS0_ARRAY_OPT
    PERM_GENUS0_ARRAY_INLINE  bool next()
    // Generate next permutation in lex order.
    // Return false if current was the last.
    {
        if ( Z == 0 )  return false;  // current is last (also for n <= 1)

        // Rightmost position k where P[k] can be increased
        // (position n-1 never can, and Z != 0 guarantees termination):
        ulong k = n - 2;
        while ( 0 == ((Z >> k) & 1) )  --k;

        const ulong pk = P[k];
        const ulong gu = GU[k];  // gap ends u = U[k], U[u], ..., n
        const ulong j = 1 + ( pk > k ? pk : k );  // new value of P[k]
        // Minimum of block of k: if pk <= k then k is a fixed point or
        // closes its cycle, so pk is the minimum; else pk is the target of
        // the arc (k, pk), and B[] is valid for targets.
        // (B[pk] is read in any case, so the selection needs no branch.)
        const ulong bp = B[pk];
        const ulong b = ( pk > k ? bp : pk );

        // Gap ends of the new completion: j, and those of k:
        const ulong G = (1UL << j) | gu;

        // Update Z: positions below k are unchanged.
        // A position y > k (fixed point, or target closing its cycle)
        // can be increased iff y+1 < U[y], i.e., iff y+1 is not in G.
        // Position k (now P[k]=j) can be increased iff j+1 < U[k],
        // i.e., iff j+1 is not in G (as j < U[k] = lowest bit of gu).
        Z = (Z & LO[k]) | (HI[k] & ~(G >> 1))
            | ((ulong)(((G >> (j + 1)) & 1) == 0) << k);


        // Fill (only stores, and loads of B[] of targets):
        P[k] = j;
        // Elements strictly inside the new arc: fixed points in the gap
        // ending at j, so their chain of gap ends is G:
        for (ulong y=k+1; y<j; ++y)  { P[y] = y;  GU[y] = G; }

        // Element j joins the block of k and (lex-minimal) closes it:
        P[j] = b;  B[j] = b;  GU[j] = gu;

        // Remaining elements: for each gap end v in gu (ascending), fixed
        // points up to v, then v closes its cycle (v < n is the target of a
        // pending arc, its B[v] and GU[v] are valid):
        ulong g = gu;  // bits of gap ends v, U[v], ..., n
        ulong x = j;
        while ( true )
        {
            const ulong v = lowest_one_idx(g);
            for (ulong y=x+1; y<v; ++y)  { P[y] = y;  GU[y] = g; }
            if ( v >= n )  break;
            P[v] = B[v];
            x = v;
            g &= g - 1;  // next gap end
        }

        return true;
    }
#else  // PERM_GENUS0_ARRAY_OPT
    bool next()
    // Generate next permutation in lex order.
    // Return false if current was the last.
    {
        if ( n <= 1 )  return false;

        // Find rightmost position k where P[k] can be increased.
        // The next value is max(P[k], k) + 1 (closing value B[k] <= k
        // is followed by k+1), it must be less than U[k].
        ulong k = n - 1;
        ulong j;
        while ( (j = 1 + ( P[k] > k ? P[k] : k )) >= U[k] )
        {
            if ( k == 0 )  return false;  // current is last
            --k;
        }

        // New arc (k, j), block of k continues with j:
        const ulong u = U[k];  // end of gap enclosing the block of k
        const ulong b = B[k];  // minimum of block of k
        P[k] = j;

        // Elements strictly inside the new arc: fixed points in gap ending at j:
        for (ulong y=k+1; y<j; ++y)  { P[y] = y;  B[y] = y;  U[y] = j; }

        // Element j joins the block of k and (lex-minimal) closes it:
        P[j] = b;  B[j] = b;  U[j] = u;

        // Remaining elements: walk the chain of pending arc targets
        // x = U[j], U[U[j]], ... (all of them have valid B[] and U[]).
        ulong x = j;
        while ( true )
        {
            const ulong v = U[x];  // end of gap containing elements after x
            for (ulong y=x+1; y<v; ++y)  { P[y] = y;  B[y] = y;  U[y] = v; }
            if ( v >= n )  break;
            x = v;
            P[x] = B[x];  // target of pending arc: close cycle
        }

        return true;
    }
#endif  // PERM_GENUS0_ARRAY_OPT

    void print(const char *bla, bool dfz=false)  const
    // If dfz is true then Dots are printed For Zeros.
    { print_vec(bla, data(), n, dfz); }

    void print_cycles(const char *bla)  const
    // Print cycle form.
    // These are also non-crossing set partitions.
    { ::print_cycles(bla, data(), n); }

    bool OK()  const
    // Check internal consistency against brute force (O(n^3), for tests):
    // B[] holds the block minima of P (with PERM_GENUS0_ARRAY_OPT only
    // for targets of arcs), U[] (resp. GU[]) the gap ends, and
    // (with PERM_GENUS0_ARRAY_OPT) Z the increasable positions.
    // (The genus-0 property is checked by the test program.)
    {
        for (ulong k=0; k<n; ++k)  if ( P[k] >= n )  return false;
        for (ulong k=0; k<n; ++k)
        {
            // block minimum: minimum along the cycle of k:
            ulong bm = k;
            for (ulong y=P[k]; y!=k; y=P[y])  if ( y < bm )  bm = y;
#if defined PERM_GENUS0_ARRAY_OPT
            if ( bm != k && B[k] != bm )  return false;  // targets only
#else
            if ( B[k] != bm )  return false;
#endif
            if ( P[k] < k && P[k] != bm )  return false;  // must close cycle

            const ulong ge = gap_end(k);
#if defined PERM_GENUS0_ARRAY_OPT
            // chain of gap ends: ge, gap end of ge, ..., n:
            ulong ch = 1UL << n;
            for (ulong e=ge; e<n; e=gap_end(e))  ch |= 1UL << e;
            if ( GU[k] != ch )  return false;

            const ulong j = 1 + ( P[k] > k ? P[k] : k );
            const bool inc = ( j < ge );
            if ( inc != (bool)((Z >> k) & 1) )  return false;
#else
            if ( U[k] != ge )  return false;
#endif
        }
#if defined PERM_GENUS0_ARRAY_OPT
        if ( Z & ~all )  return false;
#endif
        return true;
    }

private:
    ulong gap_end(ulong k)  const
    // Brute force (for OK()): smallest target t > k of an arc (s, t)
    // with s < k, else n.
    {
        ulong ge = n;
        for (ulong s=0; s<k; ++s)
            if ( P[s] > k && P[s] < ge )  ge = P[s];
        return ge;
    }
};
// -------------------------


#endif  // !defined HAVE_PERM_GENUS0_ARRAY_H__
