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

#include "fxtalloca.h"

#include "fxttypes.h"


inline ulong test_noncrossing_setpart_rgs(const ulong *R, ulong n)
// Return first index where the RGS for set partitions in R[]
//   has a crossing of the set partition.
// Return 0 if R[] corresponds to a non-crossing partition.
{
    if ( n <= 3 )  return 0;  // smallest crossing partition has size 4

    // Complexity is O(n^2), but appears to really be O(n*log_2(n))
    ALLOCA(bool, F, n);  // whether value forbidden
    for (ulong j=0; j<n; ++j)  F[j] = false;

    ulong j = 1;
    do
    {
        const ulong v0 = R[j];
        if ( F[v0] )  return j;  // j>=4

        const ulong v1 = R[j-1];

        // with down step (v0 < v1), forbid values v0+1 ... v1:
        for (ulong t = v0+1; t<=v1; ++t)  F[t] = true;
    }
    while ( ++j < n );

    return 0;
}
// -------------------------

inline bool is_noncrossing_setpart_rgs(const ulong *R, ulong n)
// Return whether the RGS for set partitions in R[]
//   corresponds to a non-crossing partition.
{ return ( 0 == test_noncrossing_setpart_rgs(R, n) ); }


#endif // !defined HAVE_IS_NONCROSSING_SETPART_RGS_H__
