#if !defined  HAVE_PERM_GENUS0_CYCLES_H__
#define       HAVE_PERM_GENUS0_CYCLES_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 "perm/printcycles.h"  // print_cycles_ce()
#include "comb/comb-print.h"  // print_vec()
#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_CYCLES_OPT  // speedup by a factor of about 1.06

class perm_genus0_cycles
// Permutations of genus 0 of n elements in cycle form (n <= 63).
// There are Catalan(n) such permutations: 1, 1, 2, 5, 14, 42, 132, ...
// (OEIS sequence A000108).
// Limit n <= 63 (in both versions of next(), checked in the constructor):
// the set of used elements, plus the sentinel element n, is a bit mask in
// one word.
// 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.
//
// Cycle form: each cycle starts with its minimum (and is increasing,
// as cycles of genus-0 permutations are), cycles sorted by their minima.
// Stored as the concatenated list C[0,...,n-1] of the elements together
// with flags E[t] != 0 iff C[t] is the last element of its cycle.
//   Example: (0, 1, 4) (2, 3)  is  C = [0 1 4 2 3],  E = [0 0 1 0 1].
//
// Order: view the cycle form as sequence of tokens, one per position t:
//   token(t) = "close" if E[t] != 0, else the next element C[t+1];
// the order is lexicographic with respect to these tokens where "close"
// is smallest.  This is NOT the lex order of the array forms, though
// the first 34 objects for n=5 agree (row 35 differs).
//
// Possible tokens at position t (with e = C[t], elements C[0..t] used):
//   close, or any e' with e < e' and e+1, e+2, ..., e' all unused.
// (Unused elements greater than e and below the next used element
// form the gap containing the current cycle.)
// Lex-minimal completion: close, then all remaining (unused) elements
// in increasing order as fixed points.
// The set of used elements is kept as a bit mask in a single word
// (with sentinel bit n), so all tests are O(1) and the
// remaining elements are found via lowest_one_idx() (bits/bitlow.h).
//
// With PERM_GENUS0_CYCLES_OPT:
//  - The candidate for the increased token at each position t,
//    1 + ( E[t] ? C[t] : C[t+1] ), is stored as CAND[t], so the search
//    for the rightmost position t whose token can be increased does less
//    work per step.
//  Measured gain about 6 percent (221 vs. 209 M/s) with lowest_one_idx()
//  of FXT (bsf instruction), only 1 percent with __builtin_ctzl()
//  (tzcnt): the original code is limited by the number of instructions,
//  and the search takes only 2.67 steps on average.
//  Variants tried and found slower (not kept):
//  a bit mask of the increasable positions with prefix masks of the used
//  elements (185 instead of 213 M/s), and a sentinel position -1.
//  Faster (about 230 M/s) is keeping the end-of-cycle flags only as a
//  bit mask instead of the array E[], which changes the interface.
//
// Algorithm C (Permutations of genus 0, cycle form; this is the
// unoptimized next(), without PERM_GENUS0_CYCLES_OPT).
// Given 1 <= n <= 63, visit all cycle forms (C[0..n-1], E[0..n-1]) of
// permutations of genus 0 in token-lex order.  W is a set of elements,
// kept as a bit mask in one word; the element n (bit n) is in W always,
// a sentinel making the test c < n unnecessary.
//   C1. [Initialize.]  Set C[t] <- t, E[t] <- 1 for 0 <= t < n.
//       (The identity (0) (1) ... (n-1).)
//   C2. [Visit.]  Visit (C, E).
//   C3. [Prepare search.]  Set W <- {0, 1, ..., n}, t <- n-1.
//   C4. [Free position t.]  Set W <- W - {C[t]}, t <- t-1.
//       (Now W holds the elements C[0], ..., C[t], and n.)
//   C5. [Can token t increase?]  If E[t] = 1 (token "close") set
//       c <- C[t]+1, otherwise (token C[t+1]) set c <- C[t+1]+1.
//       If c is not in W, go to C6.  (All elements strictly between C[t]
//       and c are unused, so c is admissible iff it is unused.)
//       Otherwise, if t = 0 terminate, else go to C4.
//   C6. [Increase token t.]  Set E[t] <- 0, C[t+1] <- c, E[t+1] <- 1,
//       W <- W + {c}, s <- t+2.
//       (The cycle of C[t] continues with c, and c closes it.)
//   C7. [Fill.]  For each element x < n not in W, in increasing order,
//       set C[s] <- x, E[s] <- 1, s <- s+1.  Go to C2.
//       (Lex-minimal completion: the remaining elements as fixed points.)
// The number of cycles nc is updated along: nc <- nc - E[t] in step C4
// (before t <- t-1), nc <- nc - E[t] + 1 in step C6, nc <- nc + 1 for
// each x in step C7.
// Measured (n=16): per object, 2.67 executions of steps C4-C5 and 1.67
// elements in step C7 on average; 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 *C;    // concatenated cycles
    ulong *E;    // E[t] != 0 iff C[t] is last element of its cycle
    ulong all;   // bit mask with bits 0, 1, ..., n-1 set (elements)
    ulong nc;    // number of cycles
#if defined PERM_GENUS0_CYCLES_OPT
    ulong *CAND; // CAND[t] = 1 + ( E[t] ? C[t] : C[t+1] )
#endif

    perm_genus0_cycles(const perm_genus0_cycles&) = delete;
    perm_genus0_cycles & operator = (const perm_genus0_cycles&) = delete;
public:
    explicit perm_genus0_cycles(ulong tn)
    {
        n = tn;
        jjassert( n <= 63 );  // need one extra (sentinel) bit in a word
        C = new ulong[n+1];  // one extra element (never used) for n==0
        E = new ulong[n+1];
        all = (1UL << n) - 1;
#if defined PERM_GENUS0_CYCLES_OPT
        CAND = new ulong[n+1];
#endif
        first();
    }

    ~perm_genus0_cycles()
    {
        delete [] C;
        delete [] E;
#if defined PERM_GENUS0_CYCLES_OPT
        delete [] CAND;
#endif
    }

    const ulong* data()  const  { return C; }   // elements in cycle order
    const ulong* ends()  const  { return E; }   // end-of-cycle flags
    ulong size()  const  { return n; }
    ulong num_cycles()  const  { return nc; }

    void first()
    // Identity permutation: (0) (1) ... (n-1).
    {
        for (ulong t=0; t<n; ++t)  { C[t] = t;  E[t] = 1; }
#if defined PERM_GENUS0_CYCLES_OPT
        for (ulong t=0; t<n; ++t)  CAND[t] = t + 1;  // close -> t+1
#endif
        nc = n;
    }

#if defined PERM_GENUS0_CYCLES_OPT
    bool next()
    // Generate next cycle form in token-lex order (see class comment).
    // Return false if current was the last.
    {
        if ( n <= 1 )  return false;

        // Scan back for rightmost position t whose token can be increased.
        // used = elements in C[0,...,t] plus sentinel bit n (acts as "used"
        // element n, so no extra test for element bound n is needed).
        ulong used = all | (1UL << n);
        ulong t = n - 1;
        while ( true )
        {
            used ^= 1UL << C[t];  // C[t] becomes unused
            nc -= E[t];           // (cycle count of the prefix only)
            --t;
            // All elements between C[t] and the candidate are unused, so the
            // candidate is admissible iff it is unused (and < n, via sentinel):
            if ( 0 == (used & (1UL << CAND[t])) )  break;
            if ( t == 0 )  // current is last (C, E unchanged)
            {
                nc = 0;  // restore count of cycles (rare, no speed concern)
                for (ulong s=0; s<n; ++s)  nc += E[s];
                return false;
            }
        }

        // Position t now continues its cycle with c, c closes the cycle:
        const ulong c = CAND[t];
        nc -= E[t];  // E[t] may have been a close
        E[t] = 0;
        C[t+1] = c;
        E[t+1] = 1;
        ++nc;
        CAND[t] = c + 1;    // token c -> c+1
        CAND[t+1] = c + 1;  // close -> c+1
        used |= 1UL << c;

        // Remaining elements in increasing order as fixed points:
        ulong f = all & ~used;
        ulong s = t + 2;
        while ( f )
        {
            const ulong x = lowest_one_idx(f);
            C[s] = x;
            E[s] = 1;
            CAND[s] = x + 1;  // close -> x+1
            ++s;
            f &= f - 1;  // remove lowest bit
        }
        nc += n - (t + 2);

        return true;
    }
#else  // PERM_GENUS0_CYCLES_OPT
    bool next()
    // Generate next cycle form in token-lex order (see class comment).
    // Return false if current was the last.
    {
        if ( n <= 1 )  return false;

        // Scan back for rightmost position t whose token can be increased.
        // used = elements in C[0,...,t] plus sentinel bit n (acts as "used"
        // element n, so no extra test for element bound n is needed).
        ulong used = all | (1UL << n);
        ulong t = n - 1;
        ulong c;  // candidate for new next element after C[t]
        while ( true )
        {
            used ^= 1UL << C[t];  // C[t] becomes unused
            nc -= E[t];           // (cycle count of the prefix only)
            --t;
            // token close -> C[t]+1;  token e' -> e'+1  (where e'==C[t+1]):
            c = 1 + ( E[t] ? C[t] : C[t+1] );
            // All elements between C[t] and c are unused, so c is
            // admissible iff it is unused (and c < n, via sentinel bit):
            if ( 0 == (used & (1UL << c)) )  break;
            if ( t == 0 )  // current is last (C, E unchanged)
            {
                nc = 0;  // restore count of cycles (rare, no speed concern)
                for (ulong s=0; s<n; ++s)  nc += E[s];
                return false;
            }
        }

        // Position t now continues its cycle with c, c closes the cycle:
        nc -= E[t];  // E[t] may have been a close
        E[t] = 0;
        C[t+1] = c;
        E[t+1] = 1;
        ++nc;
        used |= 1UL << c;

        // Remaining elements in increasing order as fixed points:
        ulong f = all & ~used;
        ulong s = t + 2;
        while ( f )
        {
            C[s] = lowest_one_idx(f);
            E[s] = 1;
            ++s;
            f &= f - 1;  // remove lowest bit
        }
        nc += n - (t + 2);

        return true;
    }
#endif  // PERM_GENUS0_CYCLES_OPT

    void print(const char *bla, bool dfz=false)  const
    // Print concatenated elements.
    { 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_ce(bla, C, E, n); }

    bool OK()  const
    // Check: C is a permutation, cycles start with minimum and are increasing,
    // cycles sorted by minimum, number of cycles correct.
    // With PERM_GENUS0_CYCLES_OPT also CAND[] is checked.
    {
        if ( n == 0 )  return true;
        ulong seen = 0;
        for (ulong t=0; t<n; ++t)
        {
            if ( C[t] >= n )  return false;
            seen |= 1UL << C[t];
        }
        if ( seen != all )  return false;
        if ( E[n-1] == 0 )  return false;
        ulong cnt = 0,  last_min = 0;
        bool start = true;
        for (ulong t=0; t<n; ++t)
        {
            if ( start )
            {
                if ( t != 0 && C[t] <= last_min )  return false;
                last_min = C[t];
                start = false;
            }
            else if ( C[t] <= C[t-1] )  return false;
            if ( E[t] )  { ++cnt;  start = true; }
        }
        if ( cnt != num_cycles() )  return false;

#if defined PERM_GENUS0_CYCLES_OPT
        for (ulong t=0; t<n; ++t)
            if ( CAND[t] != 1 + ( E[t] ? C[t] : C[t+1] ) )  return false;
#endif
        return true;
    }
};
// -------------------------


#endif  // !defined HAVE_PERM_GENUS0_CYCLES_H__
